我有一个简单的反应表单,其中包含一个包含FromGroups的FormArray。
我知道这已经被问了很多次了,但我仍然不明白为什么它不能工作。我试过很多方法了。这是两个简单的例子,与我从文档中阅读并在网上找到的内容放在一起。
组件:
@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'));
}然后编辑* And,如下所示:
<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的反应形式时,我都会遇到这样的问题。我似乎找不出一种一致的方法来让它们与动态控件一起工作,就像本例中那样。请帮帮我。
发布于 2019-05-29 17:57:46
您的模板中存在问题。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>这是你的推荐人的。
发布于 2019-05-29 18:05:02
您正在使用[formControlName]='title',这将需要title是具有控件名称的变量。你可以去掉封闭的[],它会工作的很好。用作:
formControlName='title'https://stackoverflow.com/questions/56357764
复制相似问题