-
要注意的几点:FormArray 需要在FormGroup 内部.
Arr: this.fb.array([]) // formarray
});
- 定义一个formgroup, 存放你需要做循环的form. 也便于后面的添加删除表单序列. // formarray表单
this.groupForm = this.fb.group({
Arr: this.fb.array([this.createForm()]) // formarray
});
private createForm() {
returnthis.fb.group({
control1: ['', Validators.required],
control2: ['', Validators.required],
Name: ['', Validators.required],
Code: ['', Validators.required],
Level: ['', Validators.required],
Remark: [''],
});
}
-
添加和移除表单
-
// 增加表单
newForm() {
const arr = this.groupForm.get('Arr') asFormArray;
arr.push(this.createForm()); // 推送form新表单
}
- // 移除表单
removeForm(i: number) {
const arr = this.groupForm.get('Arr') asFormArray;
arr.removeAt(i); // 根据索引移除对应的表单
}
- 前台展示方法.
<form [formGroup]="groupForm" id="detail" class="am-g">
<p formArrayName="Arr">
<p *ngFor="let form of ArrForm.controls; let i=index;" [formGroupName]="i">
<input type="text" formControlName="Name">
...............
<!-- 增加移除表单 -->
<button (click)="newForm()">增加表单</button>
<button (click)="removeForm(i)">增加表单</button>
</p>
网友评论