【问题标题】:Angular select with async souce - default value使用异步源的角度选择 - 默认值
【发布时间】:2020-04-16 01:57:19
【问题描述】:

我有很多<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 的情况下实现这一点? 谢谢!

【问题讨论】:

    标签: angular typescript rxjs angular-observable


    【解决方案1】:

    使用tap 运算符。这样我们就不必手动订阅。

    试试这个:

    this.bankAccounts$ = this.httpService.getBankAccounts().pipe(tap(data=> this.form.patchValue({ bankAccountId: data[0].id });));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 2016-01-05
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      相关资源
      最近更新 更多