问题是,因为我不能硬编码我的formBuilder的所有细节,因为我需要在它的parrent formArray中动态添加formGroup。在这个formGroup中,我需要一个子formArray,它包装了用户在checkbox上选中的所有数据。但是我在这个子formArray中推送值失败。(在我的工作中,在选中复选框中的元素后,'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>`
productsLocal:public productsLocal = [ { ProductName: 'book1', ProductId: '1' }, { ProductName: 'book2', ProductId: '2' }, { ProductName: 'book3', ProductId: '3' }, { ProductName: 'book4', ProductId: '4' }, { ProductName: 'book5', ProductId: '5' }, ];
发布于 2019-04-27 11:15:26
我认为你想用表单验证来动态元素。这在ngForm中是可能的。ngForm完整示例click here
对于Ex:
<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>
https://stackoverflow.com/questions/55879355
复制