【问题标题】:How to bind the selected value of angular dropdown to an Observable of scalar value?如何将角度下拉列表的选定值绑定到标量值的 Observable?
【发布时间】:2018-06-02 04:16:49
【问题描述】:

我有一个角度材质选择组件,我想将下拉列表的选定值绑定到来自 firebase 的标量 Observable。我想在不打开组件中的 observable 的情况下做到这一点。看起来我无法使用异步管道绑定值。下面的代码抛出异常,因为 mat-select 的值不能绑定到“uiStateSvc.currentClient$ | async”。

<mat-form-field *ngIf="(store.authorizedClients$ | async)?.length > 0">
  <mat-select [(value)]="uiStateSvc.currentClient$ | async" [compareWith]="compareFn">
    <mat-option *ngFor="let client of store.authorizedClients$ | async" [value]="client"
    (onSelectionChange)="changeCurrentClient($event, client)">
      {{ client.name}}
    </mat-option>
  </mat-select>
</mat-form-field>

我正在从 firebase 中提取下拉列表的当前选定值,如下所示:

this.selectedClient$ = this.authSvc.currentUser$.pipe(
      switchMap((x: firebase.User) => {
        if (x != null) {
          return this.afs.doc(`uistate/${x.uid}`).valueChanges().map((y: any) => y.selectedclient);
        } else {
          return Observable.of(null);
        }
      })
    );

【问题讨论】:

    标签: angular firebase observable angularfire2 rxjs6


    【解决方案1】:

    您正在使用双重绑定,您不能使用管道 async 执行此操作,它仅适用于组件中的变量,下面的代码应该可以工作,请注意我将 [(value)] 更改为 [value] 所以它将从 observable 中读取 | async 选择的默认值,并将我看到的更改存储在 mat-option (onSelectionChange)="changeCurrentClient($event, client) 中,应该足够了

    <mat-form-field *ngIf="(store.authorizedClients$ | async)?.length > 0">
      <mat-select
        [value]="uiStateSvc.currentClient$ | async"
        [compareWith]="compareFn"
      >
        <mat-option
          *ngFor="let client of store.authorizedClients$ | async"
          [value]="client"
          (onSelectionChange)="changeCurrentClient($event, client)"
        >
          {{client.name}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多