Angular 带有来自服务的数据的 FormArray setValue

Angular FormArray setValue with data from Service

我对 FormArray 有疑问,可能需要一些帮助。 我有一个带有变量 FormArray 的表单,它可以工作,我可以将数据发送到后端。 问题是,我无法根据从后端收到的数据设置值。

这是 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,
});

注意:既然你实现了actorsgetter,你可以简化

form.get('actors')['controls']

至:

actors.controls

HTML

<tr
  *ngFor="let actor of actors.controls; let i = index"
  [formGroupName]="i"
>

</tr>

Sample Solution on StackBlitz