[英]Nested FormGroups in FormArray not working
我有一個簡單的反應形式與FormArray將包含FromGroups。
我知道這已被問過很多次,但我還是不知道為什么它不起作用。 我嘗試了很多方法。 這是兩個簡單的例子,與我從文檔中讀到並在網上找到的內容放在一起。
零件:
@Component({
selector: 'app-professional-info-form',
templateUrl: './professional-info-form.component.html',
styleUrls: ['./professional-info-form.component.scss']
})
export class ProfessionalInfoFormComponent implements OnInit {
protected professionalInfo: FormGroup;
constructor() { }
ngOnInit() {
this.initForm();
}
private initForm() {
this.professionalInfo = new FormGroup({
trainings: new FormArray([
new FormGroup({
institutionId: new FormControl(null, null),
title: new FormControl(null, null),
description: new FormControl(null, null),
institution: new FormControl(null, Validators.required),
grade: new FormControl(null, null),
from: new FormControl(null, Validators.required),
to: new FormControl(null, null)
})
])
});
}
}
HTML:
<form [formGroup]="professionalInfo" (ngSubmit)="onSubmit()" novalidate *ngIf="professionalInfo">
<div formArrayName="trainings">
<div *ngFor="let training of trainings.controls; index as t" [formGroupName]="t">
<input type="text" [formControlName]="title" placeholder="Titolo" />
<input type="text" [formControlName]="institution" placeholder="Istituto" />
<input type="text" placeholder="Inizio" [formControlName]="from">
<input type="text" placeholder="Fine" [formControlName]="to">
<input type="text" placeholder="Voto" [formControlName]="grade" maxlength="5">
</div>
</div>
</form>
控制台錯誤:
ERROR TypeError: Cannot read property 'controls' of undefined
at Object.eval [as updateDirectives] (ProfessionalInfoFormComponent.html:19)
如果我將此方法添加到組件:
get trainingsFormArray() {
return (<FormArray>this.professionalInfo.get('trainings'));
}
並像這樣編輯* ngFor:
<div *ngFor="let training of trainingsFormArray.controls; index as t" [formGroupName]="t">
控制台錯誤是:
ERROR Error: Cannot find control with path: 'trainings -> 0 -> '
這有點瘋狂,因為如果在初始化表單后console.log'trainingsFormArray'輸出如下:
每次我必須使用角度的反應形式時,我會遇到像這樣的問題。 我似乎無法找到使它們與動態控件一起工作的一致方法,就像在這種情況下一樣。 請幫我。
您的模板中存在問題。 Angular不知道trainings
是什么。 使用professionalInfo.controls['trainings'].controls
來訪問trainings
FormArray
的控件。
像這樣的東西:
<form
[formGroup]="professionalInfo"
(ngSubmit)="onSubmit()"
novalidate
*ngIf="professionalInfo">
<div formArrayName="trainings">
<div
*ngFor="let training of professionalInfo.controls['trainings'].controls; index as t"
[formGroupName]="t">
<input type="text" formControlName="title" placeholder="Titolo" />
<input type="text" formControlName="institution" placeholder="Istituto" />
<input type="text" placeholder="Inizio" formControlName="from">
<input type="text" placeholder="Fine" formControlName="to">
<input type="text" placeholder="Voto" formControlName="grade" maxlength="5">
</div>
</div>
</form>
這是你的參考的工作樣本StackBlitz 。
您正在使用[formControlName]='title'
,這將需要title
為具有控件名稱的變量。 你可以擺脫封閉的[]
,它會工作正常。 用於:
formControlName='title'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.