可以有许多不同的方法来做到这一点。我现在只分享两种方法,如果你觉得这些方法中的任何一种都不能满足你的用例,我们可以考虑另一种方法(前提是你提供更多关于你想要在这里实现的目标的信息) .
方法一:
您的组件上有两个属性:
form$: Observable<FormGroup>;
list: Array<Element>;
一旦您获得 API 响应,而不是 subscribe 给它,您 map 它并生成一个表单,同时还将响应的值分配给您声明的 list 属性。像这样的:
this.form$ = this.service.getElements()
.pipe(
map((list: Array<Element>) => {
this.list = list;
return this.fb.group({
elementId: [list[0].id],
elementDescription: [list[0].description]
});
})
);
然后你在模板中使用它,有点像这样:
<form
*ngIf="form$ | async as form"
[formGroup]="form">
<label for="">Element Id: </label>
<select formControlName="elementId">
<option
*ngFor="let element of list"
[value]="element.id">
{{ element.id }}
</option>
</select>
<br>
<label for="">Element description: </label>
<select formControlName="elementDescription">
<option
*ngFor="let element of list"
[value]="element.description">
{{ element.description }}
</option>
</select>
</form>
方法二:
您可能希望将列表和FormGroup 合并在一起。所以你可以在你的组件中创建一个属性:
elementListWithForm$: Observable<{ list: Array<Element>, form: FormGroup }>;
然后你会像这样分配一个值:
this.elementListWithForm$ = this.service.getElements()
.pipe(
map((list: Array<Element>) => ({
form: this.fb.group({
elementId: [list[0].id],
elementDescription: [list[0].description]
}),
list,
}))
);
然后你可以像这样在模板中使用它:
<form
*ngIf="(elementListWithForm$ | async) as formWithList"
[formGroup]="formWithList.form">
<label for="">Element Id: </label>
<select formControlName="elementId">
<option
*ngFor="let element of formWithList.list"
[value]="element.id">
{{ element.id }}
</option>
</select>
<br>
<label for="">Element description: </label>
<select formControlName="elementDescription">
<option
*ngFor="let element of formWithList.list"
[value]="element.description">
{{ element.description }}
</option>
</select>
</form>
这里有一个Working Code Sample on StackBlitz 供您参考。
PS:这种方法的灵感来自我在一篇关于increasing the performance of a deeply nested reactive form in Angular for AngularInDepth 的文章中使用的方法。您可能也想检查一下。
希望这会有所帮助。 :)