我有一個 FormArray 問題,可能需要一些幫助。我有一個帶有變數 FormArray 的表單,它可以作業,我可以將資料發送到后端。問題是,我無法從后端收到的資料中設定值。
這是打字稿代碼:
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>
所以我的問題是:如何從獲得的資料movieService在actors陣列?
actors: this.movie.actors 不起作用,我知道我必須遍歷陣列但不知道如何。
編輯:好的,我看到我從陣列中獲得了第一個物件,但是如果我添加更多演員,它只會顯示第一個。
uj5u.com熱心網友回復:
假設:
預計收到的 API 回應資料將是:
{
"title": "James Bond 007",
"actors": [
{ "id": 5, "role": "test", "actor": "test" },
{ "id": 6, "role": "test", "actor": "test2" }
]
}
我認為不能直接patchValue為FormArray. 相反,迭代movie.actorswithmap以推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>
StackBlitz 上的示例解決方案
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/330860.html
