this.form = this.fb.group({
name: '',
addresses: this.fb.array([])
})
this.addresses = this.form.get('addresses') as FormArray;
this.addresses.push(this.fb.group({
street: '',
city: '',
state: '',
zip: ''
}));
this.addresses.push(this.fb.group({
street: '',
city: '',
state: '',
zip: ''
}));
this.form.patchValue({
addresses: [
{ street: '123 Main St', city: 'Anytown' },
{}
]
});
注意,我们使用对象数组来更新地址,同时留空第二个对象以保持其原始值。如果我们不这样做,第二个地址将被删除。
完整示例代码如下:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-address-form',
templateUrl: './address-form.component.html',
styleUrls: ['./address-form.component.css']
})
export class AddressFormComponent implements OnInit {
form: FormGroup;
addresses: FormArray;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form = this.fb.group({
name: '',
addresses: this.fb.array([])
});
this.addresses = this.form.get('addresses') as FormArray;
this.addresses.push(this.fb.group({
street: '',
city: '',
state: '',
zip: ''
}));
this.addresses.push(this.fb.group({
street: '',
city: '',
state: '',
zip: ''
}));
}
updateAddresses() {
this.form.patchValue({
addresses: [
{ street: '123 Main St', city: 'Anytown' },
{}
]
});
}
}