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-option *ngFor=" let country of countryList 
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)

janpauldahlke profile image
jan paul

bump* anyhting here?

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git