我在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应该解决此问题,请确保访问讨论。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句