[英]How can I access a properties of complex nested FormGroup
I am trying to learn reactive forms in Angular.我正在尝试在 Angular 中学习反应式 forms。 I am able to write to all properties BUT numb, alts, letter and text.
我能够写入所有属性,但 numb、alts、字母和文本。
**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我收到此错误: 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
我找到了这个例子,但我无法理解https://stackblitz.com/edit/angular-nested-reactive-form-eg-na1ctu?file=src%2Fapp%2Fapp.component.html
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. “答案”在“测试”中,这就是为什么它返回 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.编辑:要访问字母或文本,您可以执行以下操作:您必须为此使用索引才能知道要获取 formArray 中的哪个 formGroup。
get textArray(index: number): FormArray {
return this.answerArray().at(index).get('alts').get('text') as FormArray;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.