无法在angular6中使用addControl()多次添加同一数组

时间:2018-09-26 06:11:00

标签: javascript json angular frontend angular6

这是我的杰森:

{"id":"","title":"","areas":[{"areaId":"","type":"","position":"","parts":[]}]}

现在,我想根据用户要求将areas[]数组添加多次, 当我使用其他名称时每次插入数组时。 例如:

{"id":"","title":"","areas":[{"areaId":"","type":"","position":"","parts":[]}],"areas2":[{"areaId":"","type":"","position":"","parts":[]}],"areas3":[{"areaId":"","type":"","position":"","parts":[]}]}

每次我都希望Arary的名称只能是区域。

这是我添加数组的代码:

let areas = new FormArray([
    new FormGroup({
        areaId : new FormControl(''),
        type : new FormControl(''),
        position : new FormControl(''),
        parts : new FormArray([])
    })
]); 

this.form.addControl('areas', areas);

2 个答案:

答案 0 :(得分:0)

您每次都在创建新的表单数组。您应该在此处添加新的表单控件。

const formGroup= new FormGroup({
        areaId : new FormControl(''),
        type : new FormControl(''),
        position : new FormControl(''),
        parts : new FormArray([])
    })

areas.push(formGroup);

答案 1 :(得分:0)

您可以使用 get 创建formArray实例并在其中推送新控件

像这样

.ts

 formGropup = this.formBuilder({
      areas : this.formBuilder.array([])
    })

/*Initlaize formArray*/
    get areaCollection(): FormArray {
        return this.pecRegForm.get('areas') as FormArray;
    };

 /*Initlaize formcontrols*/
    createArea(): FormGroup {
        return this.fb.group({
            areaId : new FormControl(''),
            type : new FormControl(''),
            position : new FormControl(''),
            parts : new FormArray([])
        });
    }

    /* Here you can push new formGroup*/
    addMoreAreas() {
        this.censusCollection.push(this.createArea());
    }

.html

<div class="col-md-4" *ngFor="let item of formGropup.get('areas').controls; let i = index;" [formGroupName]="i">
   <input formControlName="areas" type="text" placeholder="Id"> 
   <input formControlName="type" type="text" placeholder="Id">  
   <!-- and so on -->                           
</div>