The problem is, because I can't hard code all the details of my formBuilder as I need dynamically add formGroup in its parrent formArray. And in this formGroup I need a child formArray which wrap up all the data that the user checked on the checkbox. but I failed push value in this child formArray. (in my work, the value of 'this.prodArray' is empty after I selected the element in the checkbox.) this is my code:`
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'
},
];