我的 Angular 应用程序中有一个自定义表单控制组件,它实现了ControlValueAccessor
界面。
但是,我想访问FormControl
实例,与我的组件关联。我正在使用反应式形式FormBuilder
并使用提供表单控制formControlName
属性。
那么,我如何访问FormControl
来自我的自定义表单组件内部的实例?
该解决方案诞生于讨论在 Angular 存储库中。请务必阅读它,如果您对此问题感兴趣,最好参与。
我研究过的代码FormControlName
指令,它启发我编写了以下解决方案:
@Component({
selector: 'my-custom-form-component',
templateUrl: './custom-form-component.html',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: CustomFormComponent,
multi: true
}]
})
export class CustomFormComponent implements ControlValueAccessor, OnInit {
@Input() formControlName: string;
private control: AbstractControl;
constructor (
@Optional() @Host() @SkipSelf()
private controlContainer: ControlContainer
) {
}
ngOnInit () {
if (this.controlContainer) {
if (this.formControlName) {
this.control = this.controlContainer.control.get(this.formControlName);
} else {
console.warn('Missing FormControlName directive from host element of the component');
}
} else {
console.warn('Can\'t find parent FormGroup directive');
}
}
}
我正在注入父级FormGroup
到组件,然后获取特定的FormControl
使用通过获得的控件名称从中获取formControlName
捆绑。
但是,请注意,该解决方案是专门针对以下用例量身定制的:FormControlName
指令用于宿主元素。在其他情况下它不会起作用。为此,您需要添加一些额外的逻辑。如果您认为这个问题应该由 Angular 解决,请务必访问讨论.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)