如何将新的表单控件推送到嵌套表单数组(父表单组是动态添加的,我不能在其上使用 getter)



问题是,因为我无法对formBuilder的所有细节进行硬编码,因为我需要在其parrent formArray中动态添加formGroup。在这个表单组中,我需要一个子表单数组,它包装了用户在复选框上选中的所有数据。但我在这个子表单数组中的推送值失败了。(在我的工作中,在复选框中选择元素后,'this.prodArray' 的值为空。这是我的代码:'

productArrayForm = this.fb.group({
    arrayRoot: this.fb.array([this.prodGroup])
  })
  get arrayRoot(){
    return this.productArrayForm.get('arrayRoot') as FormArray;
  }
  get prodGroup(): FormGroup {
    return this.fb.group ({
      array:this.fb.array([])
    })
  }
  get prodArray() {
    return this.prodGroup.get('array') as FormArray;
  }
  addOption() {
    this.arrayRoot.push(this.prodGroup);
  }
  checkProd(product: string, isChecked: boolean) {
    if (isChecked){
      this.prodArray.push(new FormControl(product));
    }
  }

for html I wrote:

<form class='mb-2' [formGroup]='productArrayForm'>
    <div formArrayName="arrayRoot">
        <div *ngFor="let li of arrayRoot.controls; let j = index" [formGroupName]='j'>
            <div class="d-flex justify-content-end">
                <button (click)='addOption()'>+</button>
                <div class="form-group">
                <div class="form-control" *ngFor="let product of productsLocal;">
                    <input type="checkbox" (change)='checkProd(product.ProductId, $event.target.checked)'> {{product.ProductName}}
                </div>
            </div>
        </div>
    </div>
</form>`

产品本地: public productsLocal = [ { ProductName: 'book1', ProductId: '1' }, { ProductName: 'book2', ProductId: '2' }, { ProductName: 'book3', ProductId: '3' }, { ProductName: 'book4', ProductId: '4' }, { ProductName: 'book5', ProductId: '5' }, ];

我认为您希望通过表单验证来动态元素。这在ngForm中是可能的。ng表单完整示例单击此处

例如:

<form role="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
    <div *ngFor="let item of allSaleItems; index as saleIndex">
        <select *ngIf="!item.batch" class="form-control font-12 p-l-0 p-r-0"
            [name]="'selectBatch' + saleIndex" [(ngModel)]="item.selectBatch" (change)="batchChange(item)"
            [ngClass]="{ 'is-invalid': f.submitted && !item.selectBatch }">
            <option value="" disabled>Product Batch Here</option>
            <option *ngFor="let pBatch of item.productBatches" [ngValue]="pBatch">{{pBatch.batch_details}}</option>
        </select>
        <div *ngIf="f.submitted && !item.selectBatch" class="invalid-feedback">
            Product batch is required
        </div>
    </div>
    <button type="submit">save</button>
</form>

最新更新