这是一个工作代码。您可以将其插入项目并进行测试。
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
private addresses: string[] = ['Address 1', 'Address 2', 'Address 3'];
private form: FormGroup;
constructor(private formBuilder: FormBuilder){}
ngOnInit(){
// Init Form
this.form = new FormGroup({
'userData': new FormGroup({
'username': new FormControl(null, [Validators.required]),
'email': new FormControl(null, [Validators.required, Validators.email])
}),
'addresses': new FormArray([])
});
// If you want to insert static data in the form. You can use this block.
this.form.setValue({
'userData': {
'username': 'Vic',
'email': 'email@email.com'
},
'addresses': [] // But the address array must be empty.
});
// And if you need to insert into the form a lot of addresses.
// For example, which belong to one user and so on.
// You must use this block.
// Go through the array with addresses and insert them into the form.
this.addresses.forEach((value) => {
const control = new FormControl(value, Validators.required);
(<FormArray>this.form.get('addresses')).push(control);
});
// Or you can use more better approach. But don't forget to initialize FormBuilder.
this.form.setControl('addresses', this.formBuilder.array(this.addresses || []));
}
}