angular - 使用异步源的角度选择 - 默认值
问题描述
我有很多<select>
绑定到 HTTP 服务(从底层 REST API 获取数据)。我试图尊重 Angular 中的反应模式,这是代码:
<select class="custom-select" formControlName="bankAccountId" >
<option *ngFor="let x of bankAccounts$ | async" [value]="x.id" >{{ x.name }}</option>
</select>
这导致用户必须手动选择选项的空白选择。我想在 select 中预先选择第一个值(在大多数情况下,用户会手动选择值)。我知道如何使用命令式模式来实现这一点。
ngOnInit() {
this.bankAccounts$ = this.httpService.getBankAccounts();
this.bankAccounts$.subscribe(data => {
this.form.patchValue({ bankAccountId: data[0].id });
});
}
有什么方法可以在不需要手动订阅 Observable 的情况下实现这一点?谢谢!
解决方案
使用水龙头运算符。这样我们就不必手动订阅。
尝试这个:
this.bankAccounts$ = this.httpService.getBankAccounts().pipe(tap(data=> this.form.patchValue({ bankAccountId: data[0].id });));
推荐阅读
- windows - 我想在批处理文件中使用 for 循环从用户那里获得很多输入
- apache-spark - 按字段对 Spark 数据帧进行重复数据删除
- javascript - 如何在 Javascript 循环中每 N 次迭代休眠一次?
- python - 如何清除使用 Keras 和 Tensorflow(作为后端)创建的模型?
- latex - 如何在简历中将对象放在中上
- f# - 指定要包含在 nupkg 中的依赖项
- swift - 使用 segue 将数据从模型移动到目标 ViewController
- javascript - 如何使用 d3 或常规 javascript 标记一个特定的散点(不是所有点)?
- regex - Perl MongoDB API - 过滤器中的正则表达式
- angular - Angular组件如何嵌套无序列表
- 段内
?