angular表单 如何往formArray中动态添加formGroup
angular form表单,需要动态添加一列,这一列中有多个control,这里需要用到formArray。这一列可以当作formGroup。相关代码如下:
一、创建一个formArray
1
2
3
4
5
6this.validateForm = this.fb.group({ categoryList: this.fb.array([]) }); get categoryList(){ return this.validateForm.get('categoryList') as FormArray }
二、往formArray中添加 formGroup
1
2
3
4this.categoryList.push(this.fb.group({ id: this.fb.control(v.id), name: this.fb.control(v.name) }))
三、html中的代码
1
2
3
4
5
6
7
8
9
10<div [formGroup] = "validateForm"> <div formArrayName="categoryList"> <div *ngFor="let item of categoryList.controls; let i=index"> <div [formGroupName]="i"> <input type="hidden" formControlName="id"> <input nz-input formControlName="name"/> </div> </div> </div> </div>
四、删除
1this.categoryList.removeAt(i)
五、表单是否修改过
1this.validateForm.dirty
保存之后,dirty修改为false
1this.validateForm.markAsPristine()