10

I have an angular material select component and I would like to bind the selected value of the dropdown to an Observable of scalar from firebase. I would like to do this without unwrapping the observable in component. It looks I cannot bind the value using async pipe. The code below throws an exception because the value of mat-select cannot be bound to "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>

I am pulling the current selected value of the dropdown from firebase like so:

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);
        }
      })
    );

1 Answer 1

5
+25

You are using double binding, you can not do that with the pipe async it only works with a variable in the component, the code bellow should work, notice I changed the [(value)] to [value] so it will read from the observable | async the default value for the select, and to store the changes I see you already have in the mat-option (onSelectionChange)="changeCurrentClient($event, client), that should be enough

<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>

Hope it helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.