在Angular 8中,可以通过在HTML中使用[formControlName]
来动态设置formControlName
。以下是一个示例:
首先,在组件中定义一个控件名称的变量,例如controlName
:
controlName: string = '';
然后,在模板中使用[formControlName]
来动态设置控件名称:
在组件中,可以编写一个方法来动态改变controlName
的值:
changeFormControlName() {
this.controlName = 'dynamicControl';
}
这样,当点击按钮时,controlName
的值将被设置为'dynamicControl'
,并且[formControlName]
将被更新为'dynamicControl'
。
请注意,为了使用动态formControlName
,你必须确保在使用之前已经实例化了FormControl
。这可以在组件的构造函数中完成:
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
dynamicControl: ['']
});
}
这里使用了FormBuilder
来创建一个名为myForm
的FormGroup
,其中包含一个名为dynamicControl
的FormControl
。
这就是在Angular 8中,根据组件动态设置formControlName
的解决方法。你可以根据自己的需求修改示例代码。