Sve*_*sen 3 typescript angular angular-reactive-forms formarray
我在 FormArray 方面遇到问题,可能需要一些帮助。\n我有一个带有变量 FormArray 的表单,它可以工作,我可以将数据发送到后端。\n问题是,我无法设置从我收到的数据中的值后端。
\n这是打字稿代码:
\nthis.form = this.fb.group({\n title: new FormControl("",[Validators.required]),\n actors: new FormArray([])\n})\n\nthis.moviesService.getMovie(this.movieId).subscribe(movieData => {\n this.movie = movieData;\n this.form.patchValue({\n title: this.movie.title,\n actors: this.movie.actors, \n })\n})\nRun Code Online (Sandbox Code Playgroud)\n然后在 html 中单击按钮,我调用此函数:
\naddActor(){\n const actorsForm = this.fb.group({\n actor: \'\',\n role: \'\'\n })\n this.actors.push(actorsForm);\n}\n\nremoveActor(i: number){\n this.actors.removeAt(i);\n}\nRun Code Online (Sandbox Code Playgroud)\n和 HTML:
\n<form [formGroup]="form" (submit)="onSubmit()">\n <table formArrayName="actors">\n <tr>\n <th colspan="2">Besetzung:</th>\n <th width="150px">\n <button type="button" mat-stroked-button color="primary" (click)="addActor()">Hinzuf\xc3\xbcgen +</button>\n </th>\n </tr>\n <tr *ngFor="let actor of form.get(\'actors\')[\'controls\']; let i=index" [formGroupName]="i">\n <td>\n Darsteller:\n <input type="text" formControlName="actor" class="form-control">\n </td>\n <td>\n Rolle:\n <input type="text" formControlName="role" class="form-control">\n </td>\n <td>\n <button (click)="removeActor(i)" mat-stroked-button color="warn">Remove</button>\n </td>\n </tr>\n </table>\n <button mat-raised-button color="primary" type="submit">Film speichern</button>\n</form>\nRun Code Online (Sandbox Code Playgroud)\nmovieService所以我的问题是:\n如何从数组中获取数据actors?
actors: this.movie.actors不起作用,我知道我必须遍历数组,但不知道如何。
编辑:\n好吧,我看到我从数组中获得了第一个对象,但如果我添加更多演员,它只会显示第一个。
\n假设:
预计收到的 API 响应数据将是:
{
"title": "James Bond 007",
"actors": [
{ "id": 5, "role": "test", "actor": "test" },
{ "id": 6, "role": "test", "actor": "test2" }
]
}
Run Code Online (Sandbox Code Playgroud)
我认为不能直接patchValue用于FormArray. 相反,迭代movie.actors以便map推FormGroup送到actors FormArray。
{
"title": "James Bond 007",
"actors": [
{ "id": 5, "role": "test", "actor": "test" },
{ "id": 6, "role": "test", "actor": "test2" }
]
}
Run Code Online (Sandbox Code Playgroud)
注意:由于您实现了actorsgetter,因此可以简化
form.get('actors')['controls']
Run Code Online (Sandbox Code Playgroud)
到:
actors.controls
Run Code Online (Sandbox Code Playgroud)
超文本标记语言
<tr
*ngFor="let actor of actors.controls; let i = index"
[formGroupName]="i"
>
</tr>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12561 次 |
| 最近记录: |