问题是,因为我无法对formBuilder的所有细节进行硬编码,因为我需要在其父级formArray中动态添加formGroup。在这个formGroup中,我需要一个子formArray,它包装用户在复选框上检查的所有数据。但是我在这个子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'
},
];
答案 0 :(得分:0)
我认为您想通过表单验证来动态化元素。在ngForm中是可能的。 ngForm完整示例click here
例如:
<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>