I have a child component where I have two FormGroup
. One with simple FormControl and other is with FormArray
. I followed this stackblitz example as well as many other which is related to FormArray
still no idea why it is not working.
custom-condition.ts
@Input() parentForm: FormGroup;
customConditions: FormGroup
ngOnInit() {
this.initForm()
}
initForm(){
this.customConditions = this.fb.group({
custom: this.fb.array([])
});
this.getCustomArray.push(this.getCustomConditionController())
this.parentForm.addControl("CustomConditions", this.customConditions);
}
get getCustomArray(): FormArray {
return <FormArray>this.customConditions.get("custom")
}
getCustomConditionController(): FormGroup {
return this.fb.group({
ConditionArabic: this.fb.control(""),
ConditionEnglish: this.fb.control("")
});
}
addCustomConditions() {
this.getCustomArray.push(this.getCustomConditionController())
}
removeCustomConditions(i: number) {
this.getCustomArray.removeAt(i)
}
isLastRow(rowIndex: any) {
return this.customConditions.controls.length == rowIndex + 1
}
custom-condtion.html
<div class="row" [formGroup]="customConditions">
<ng-container formArrayName="custom">
<div class="col-12" *ngFor="let fg of getCustomArray.controls; let i = index">
<div class="row mt-3 mb-3" [formGroupName]='fg'>
<div class="col-4">
<div class="form-group">
<label for="ConditionEnglish{{i}}" class="control-label">Condition English</label>
<input
type="text"
class="form-control"
tabindex="{{i+1}}"
id="ConditionEnglish{{i}}"
formControlName="ConditionEnglish"
autocomplete="off" />
</div>
</div>
<div class="col-4">
<div class="form-group">
<label for="ConditionArabic{{i}}" class="control-label">Condition Arabic</label>
<input
type="text"
name="ConditionArabic"
class="form-control"
tabindex="{{i+1}}"
id="ConditionArabic{{i}}"
formControlName="ConditionArabic"
autocomplete="off" />
</div>
</div>
<div class="col-4">
<span class="file-add" *ngIf="i > 0">
<a (click)="removeCustomConditions(i)"><i class="fal fa-trash-alt"></i></a>
</span>
<span class="file-add" *ngIf="isLastRow(i)">
<a (click)="addCustomConditions()"><i class="fal fa-plus-circle"></i></a>
</span>
</div>
</div>
</div>
</ng-container>
</div>
Error getting:
ERROR Error: Cannot find control with path: 'custom -> [object Object]'
also this.customConditions.get("custom")
returns empty array after component loading and that is why getCustomArray.controls
in empty so html is not rendering.
What am I doing wrong here?
question from:
https://stackoverflow.com/questions/65935959/angular-formarray-returns-null-on-ngoninit 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…