Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind the selected value of angular dropdown to an Observable of scalar value?

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);
        }
      })
    );
like image 924
user2202866 Avatar asked Jun 02 '18 04:06

user2202866


1 Answers

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

like image 56
Gabriel Guerrero Avatar answered Sep 26 '22 14:09

Gabriel Guerrero