在Angular 6中,可以使用FormGroup
的get
方法来获取子表单控件,并使用循环遍历来填充表单。
以下是一个示例代码:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
myForm: FormGroup;
ngOnInit() {
this.myForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormGroup({
street: new FormControl(''),
city: new FormControl(''),
state: new FormControl(''),
zip: new FormControl('')
})
});
}
populateForm() {
const data = {
firstName: 'John',
lastName: 'Doe',
address: {
street: '123 Main St',
city: 'New York',
state: 'NY',
zip: '12345'
}
};
for (const controlName in this.myForm.controls) {
if (this.myForm.controls.hasOwnProperty(controlName)) {
if (this.myForm.get(controlName) instanceof FormGroup) {
const subForm = this.myForm.get(controlName) as FormGroup;
for (const subControlName in subForm.controls) {
if (subForm.controls.hasOwnProperty(subControlName)) {
subForm.get(subControlName).patchValue(data[controlName][subControlName]);
}
}
} else {
this.myForm.get(controlName).patchValue(data[controlName]);
}
}
}
}
}
在上面的示例中,我们首先创建了一个FormGroup
,其中包含了一个子表单控件address
。然后,在populateForm
方法中,我们使用循环遍历myForm.controls
来获取每个控件,并使用patchValue
方法来填充相应的值。
这样,当调用populateForm
方法时,表单的值将会被填充为示例数据中的值。