DEV Community

Prayatna Bhattarai
Prayatna Bhattarai

Posted on • Updated on

TIL: How to use async pipe and populate mat-select

I was trying to use async | pipe directly on the view to get all the country list and populate my mat-select dropdown. The countrySelector component has a countryList$ observable which gets all the country from a service like so:

 ...
  ngOnInit(): void {
    this.countryList$ = this.countryService.getCountries();
  }
 ...
Enter fullscreen mode Exit fullscreen mode

Then in my view, I use ng-container with an *ngIf clause to check if the country list is available.

<ng-container *ngIf="countryList$ | async as countryList">
Enter fullscreen mode Exit fullscreen mode

I then use the countryList and populate the mat-select which uses *ngFor to go through the list of countries and add a mat-option for each of the item. It also has a poperty onSelectionChange which fires an event when a selection is changed. My final view will look something like this:

<ng-container *ngIf="countryList$ | async as countryList">
 <mat-select>
  <mat-option *ngFor=" let country of countryList 
     [value]="country"
     (onSelectionChange)="changeCurrentSelection($event, 
     country)">                  
    {{country.name}}
  </mat-option>
 </mat-select>
</ng-container>
Enter fullscreen mode Exit fullscreen mode

This way I can populate the mat-option without having to assign it to any variable on the component and directly use it in the view.

Please let me know if there are any other better ways to do it.

Top comments (1)

Collapse
 
janpauldahlke profile image
jan paul

bump* anyhting here?