在Angular 6中,可以使用addControl
方法来添加子表单组。以下是一个包含代码示例的解决方法:
FormGroup
中定义一个子表单组:import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
parentForm: FormGroup;
ngOnInit() {
this.parentForm = new FormGroup({
// 在这里定义父表单的控件
firstName: new FormControl(''),
lastName: new FormControl(''),
// 添加一个子表单组
childForm: new FormGroup({
age: new FormControl(''),
gender: new FormControl('')
})
});
}
// 添加子表单组的方法
addChildForm() {
const childForm = new FormGroup({
age: new FormControl(''),
gender: new FormControl('')
});
// 使用addControl方法将子表单组添加到父表单中
this.parentForm.addControl('childForm', childForm);
}
}
通过以上步骤,您可以使用.addControl
方法在Angular 6中添加子表单组。