在表单控件中使用方括号绑定语法,例如:
然后在组件中动态初始化表单控件名称,例如:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
formGroup: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.formGroup = this.formBuilder.group({});
}
addControl() {
const dynamicName = 'dynamicControl';
this.formGroup.addControl(
dynamicName,
new FormControl('', Validators.required)
);
// Set dynamicName as the name of the form control
this.formGroup.controls[dynamicName].setValue('', { onlySelf: true });
}
}
这样就可以在模板中动态添加表单控件并绑定控件名称。
上一篇:Angular中表单不显示