簡體   English   中英

無法在angular6中使用addControl()多次添加同一數組

[英]unable to add the same array more than one time using addControl() in 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);

您每次都在創建新的表單數組。 您應該在此處推動添加新的表單控件。

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

areas.push(formGroup);

您可以使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM