/

angular表单 如何往formArray中动态添加formGroup

angular form表单,需要动态添加一列,这一列中有多个control,这里需要用到formArray。这一列可以当作formGroup。相关代码如下:

一、创建一个formArray

1
2
3
4
5
6
this.validateForm = this.fb.group({ categoryList: this.fb.array([]) }); get categoryList(){ return this.validateForm.get('categoryList') as FormArray }

二、往formArray中添加 formGroup

1
2
3
4
this.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>

四、删除

1
this.categoryList.removeAt(i)

五、表单是否修改过

1
this.validateForm.dirty

保存之后,dirty修改为false

1
this.validateForm.markAsPristine()
作者:liuk123标签:angular分类:angular

本文是原创文章,采用 CC BY-NC-ND 4.0 协议, 完整转载请注明来自 liuk123