Reputation: 89
I am trying to learn reactive forms in Angular. I am able to write to all properties BUT numb, alts, letter and text.
**COMPONENT.TS**
createForm() {
this.userForm = this.fb.group({
fname: ['', [Validators.required]],
lname: ['', [Validators.required]],
email: ['', [Validators.email, Validators.required]],
facility: ['', [Validators.required]],
position: [''],
test: this.fb.group({
name: [''],
id: [''],
date: [''],
scored: [''],
wrong: [''],
duration: [''],
answers: this.fb.array ([
this.fb.group({
numb: [''],
alts: this.fb.group({
letter: this.fb.array([]),
text: this.fb.array([])
})
})
])
})
})
}
get answerArray() {
return this.userForm.get("answers") as FormArray;
}
**COMPONENT.HTML**
<form [formGroup]="userForm">
<div formGroupName="test">
<div formArrayName="answers">
<div *ngFor="let ans of answerArray.controls; let i = index">
<div [formGroupName]="i">
<input type="text" formControlName="">
</div>
</div>
</div>
</div>
</form>
<pre>{{ userForm.value | json}}</pre>
I get this error: core.js:6241 ERROR TypeError: Cannot read property 'controls' of null
Please if anyone can help me. I found this example but I was not able to understand https://stackblitz.com/edit/angular-nested-reactive-form-eg-na1ctu?file=src%2Fapp%2Fapp.component.html
Upvotes: 3
Views: 2844
Reputation: 479
Try this one :
get answerArray() {
return this.userForm.controls['test'].get("answers") as FormArray;
}
or
get answerArray() {
return this.userForm.get("test.answers") as FormArray;
}
or
get answerArray() {
return this.userForm.get(["test","answers"]) as FormArray;
}
"answers" is inside "test" that's why its returning undefiend.
Edit: to Access letter or text you can do the following: you must use an index for this one to know which formGroup in the formArray to get.
get textArray(index: number): FormArray {
return this.answerArray().at(index).get('alts').get('text') as FormArray;
}
Upvotes: 7