从Angular中的自定义表单组件访问FormControl

前端之家收集整理的这篇文章主要介绍了从Angular中的自定义表单组件访问FormControl前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的Angular应用程序中有一个自定义表单控件组件,它实现了ControlValueAccessor接口。

但是,我想访问与我的组件关联的FormControl实例。我正在使用FormBuilder的反应形式,并使用formControlName属性提供表单控件。

那么,我如何从自定义表单组件内部访问FormControl实例?

解决方案诞生于Angular存储库中的 the discussion。如果您对此问题感兴趣,请务必阅读或更好地参与。

我已经研究了FormControlName指令的代码,它激发了我编写以下解决方案的灵感:

@H_301_11@@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注入组件,然后使用通过formControlName绑定获得的控件名从中获取特定的FormControl。

但是,请注意,此解决方案是专门针对在host元素上使用FormControlName指令的用例而定制的。它在其他情况下不起作用。为此,您需要添加一些额外的逻辑。如果您认为这应该由Angular解决,请务必访问the discussion

猜你在找的Angularjs相关文章