我有一个问题与FormArray,可能需要一些帮助。我有一个带有变量formmarray的表单,它可以工作,我可以将数据发送到后端。问题是,我不能从我从后端收到的数据设置值。
这是Typescript代码:
this.form = this.fb.group({
title: new FormControl("",[Validators.required]),
actors: new FormArray([])
})
this.moviesService.getMovie(this.movieId).subscribe(movieData => {
this.movie = movieData;
this.form.patchValue({
title: this.movie.title,
actors: this.movie.actors,
})
})
然后点击按钮在html中我调用这个函数:
addActor(){
const actorsForm = this.fb.group({
actor: '',
role: ''
})
this.actors.push(actorsForm);
}
removeActor(i: number){
this.actors.removeAt(i);
}
和HTML:
<form [formGroup]="form" (submit)="onSubmit()">
<table formArrayName="actors">
<tr>
<th colspan="2">Besetzung:</th>
<th width="150px">
<button type="button" mat-stroked-button color="primary" (click)="addActor()">Hinzufügen +</button>
</th>
</tr>
<tr *ngFor="let actor of form.get('actors')['controls']; let i=index" [formGroupName]="i">
<td>
Darsteller:
<input type="text" formControlName="actor" class="form-control">
</td>
<td>
Rolle:
<input type="text" formControlName="role" class="form-control">
</td>
<td>
<button (click)="removeActor(i)" mat-stroked-button color="warn">Remove</button>
</td>
</tr>
</table>
<button mat-raised-button color="primary" type="submit">Film speichern</button>
</form>
我的问题是:我如何从actors
阵列中的movieService
获得数据?
actors: this.movie.actors
不工作,我知道我必须通过数组迭代,但不知道如何。
编辑:好的,我看到我从数组中获得了第一个对象但是如果我添加更多的参与者它只会显示第一个。
假设:
期望收到的API响应数据为:
{
"title": "James Bond 007",
"actors": [
{ "id": 5, "role": "test", "actor": "test" },
{ "id": 6, "role": "test", "actor": "test2" }
]
}
我不认为可以直接patchValue
为FormArray
。相反,用map
迭代movie.actors
,以便将FormGroup
推入actors
FormArray
。
this.movie.actors.map(
(actor: any) => {
const actorsForm = this.fb.group({
actor: actor.actor,
role: actor.role,
});
this.actors.push(actorsForm);
}
);
this.form.patchValue({
title: this.movie.title,
});
注意:既然你实现了actors
getter,你可以简化
form.get('actors')['controls']
:
actors.controls
HTML<tr
*ngFor="let actor of actors.controls; let i = index"
[formGroupName]="i"
>
</tr>
StackBlitz的样例解决方案