在这段Angular 2+代码中,我有一个FormArray,其中包含需要验证的字段。 FormArray是视频列表,每个视频都有一个说明和一个值。值字段为必填。
问题是我遇到错误Cannot find control with path: 'videos -> 0 -> '
。我查看了其他答案,调整了代码,但错误仍然存在。有什么想法可以解决此问题吗?
@Component({
selector: 'my-app',
template: `
<form [formGroup]="exerciseForm">
<div formArrayName="videos">
<div *ngFor="let video of videoArray.controls; let i=index" [formGroupName]="i">
<label>{{video.descrip}}</label>
<input type="text" [formControlName]="val" />
<label *ngIf="exerciseForm.controls['videos'].controls[i].hasError('required') &&
(exerciseForm.controls['videos'].controls[i].touched">
Video identifier is required
</label>
</div>
</div>
</form>
`
})
export class App implements OnInit{
constructor(private formBuilder: FormBuilder){}
videos:any[] = [ {descrip: 'Descrip 1', val: 'Val 1' },
{descrip: 'Descrip 2', val: 'Val 2' } ];
videoArray: FormArray = new FormArray([]);
ngOnInit(){
this.exerciseForm = this.formBuilder.group({
'videos': this.addVideoArray()
});
}
addVideoArray(): FormArray {
this.videos.forEach((video: any) => {
this.videoArray.push(this.getVideo(video));
});
return this.videoArray;
}
getVideo(video): FormGroup{
return this.formBuilder.group({
descrip: this.formBuilder.control(video.descrip, [Validators.required]),
val: this.formBuilder.control(video.val, [Validators.required])
});
}
}
答案 0 :(得分:2)
替换:
<input type="text" [formControlName]="val" />
收件人:
<input type="text" formControlName="val" />
答案 1 :(得分:1)
您需要更改定义和访问videoArray
@Component({
selector: 'my-app',
template: `
<form [formGroup]="exerciseForm">
<div formArrayName="videos">
<div *ngFor="let video of exerciseForm.controls.videos.controls; let i=index">
<div [formGroupName]="i">
<label>{{video.controls.descrip.value}}</label>
<input type="text" formControlName="val" />
<label *ngIf="video.controls.val.hasError('required') && video.controls.val.touched">
Video identifier is required
</label>
</div>
</div>
</div>
</form>
`
})
export class App implements OnInit{
constructor(private formBuilder: FormBuilder){}
videos:any[] = [ {descrip: 'Descrip 1', val: 'Val 1' },
{descrip: 'Descrip 2', val: 'Val 2' } ];
ngOnInit(){
this.exerciseForm = this.formBuilder.group({
'videos': this.formBuilder.array([])
});
this.addVideoArray();
}
addVideoArray() {
const videoArray = (this.exerciseForm.controls.videos as FormArray);
this.videos.forEach((video: any) => {
videoArray.push(this.getVideo(video));
});
}
getVideo(video): FormGroup{
return this.formBuilder.group({
descrip: [video.descrip, [Validators.required]],
val: [video.val, [Validators.required]]
});
}
}