需求:在页面中默认显示一组联系方式,通过点击按钮可以添加更多联系方式组
export class HelloComponent implements OnInit {// 表单contactForm: FormGroup = new FormGroup({contacts: new FormArray([])})// 获取表单中的 contactForm.contactsget contacts() {return this.contactForm.get("contacts") as FormArray}// 添加联系方式addContact() {// 联系方式const myContact: FormGroup = new FormGroup({name: new FormControl(),address: new FormControl(),phone: new FormControl()})// 向联系方式数组中添加联系方式this.contacts.push(myContact)}// 删除联系方式removeContact(i: number) {this.contacts.removeAt(i)}ngOnInit() {// 添加默认的联系方式this.addContact()}onSubmit() {console.log(this.contactForm.value)}}
<form [formGroup]="contactForm" (submit)="onSubmit()"><div formArrayName="contacts"><div *ngFor="let contact of contacts.controls; let i = index" [formGroupName]="i"><input type="text" formControlName="name" /><input type="text" formControlName="address" /><input type="text" formControlName="phone" /><button (click)="removeContact(i)">删除联系方式</button></div></div><button (click)="addContact()">添加联系方式</button><button>提交</button></form>
