Here's the link to my StackBlitz Demo App
I am trying to dynamically add input fields using FormBuilder array() method.
To get a clear vision look at my ngOnInit() and dependent methods
stackForm: FormGroup;
get work(): FormArray {
return this.stackForm.get('work') as FormArray;
}
get highlights(): FormArray {
return this.stackForm.get('work.highlights') as FormArray;
}
ngOnInit() {
this.stackForm = new FormGroup({
'work': this.fb.array([this.buildWork()])
})
}
buildWork(): FormGroup {
return this.fb.group({
company: '',
position: '',
summary: '',
highlights: this.fb.array([this.buildHighlights()])
});
}
buildHighlights(): FormControl {
return new FormControl()
}
HTML implementation is like this:
<div formArrayName="highlights">
<div [formGroupName]="j"
*ngFor="let hg of highlights.controls; let j=index">
<!-- input element -->
</div>
</div>
But I am getting this error message on console, and my input fields are not shown.
ERROR Error: ctx_r0.highlights is null
UPDATE: Thanks to @Lotte-Lemmens, helped me figure out the null issue.
However, I cannot see a textbox on load. Maybe because it was null, how may I pass an empty value from the component so that it loops for once and I can see the textbox as well.
UPDATE: Thanks to @Eldar, I am able to see the textbox now, and add more for new highlights. On the Updated StackBlitz, there's still problem updating value of stackForm when hightlight is added. When I click on new highlight and add new highlight, the value is not added inside the highlights array in stackForm.value, only the first value is added.
But if i edit the first highlight (to recreate this issue, add multiple highlights first), all others are added into array at once.
Thanks.