Search code examples
angularrxjsangular2-observablesasync-pipe

How to set empty and default value of a select element when using async pipes in Angular


I'm trying to use async pipe in my Angular application, and this in my Typescript file:

this.mySupplierList$ = this._mySupplierService.getSupplierList();

and the HTML file:

<select>
  <option *ngFor="let supplier of supplierList$ | async" [ngValue]="supplier">{{supplier.Name}}</option>
</select>

I have two questions:

  1. How can I set the default value of the select to the first or last supplier in mySupplierList?

  2. How can I add an empty supplier item as the first element of the select?


Solution

    1. Use ngModel to set a default value.
    2. Add a tag without any value for empty supplier item.
    <select  [(ngModel)]="yourModel">
      <option>Empty</option>
      <option *ngFor="let supplier of supplierList$ | async" [ngValue]="supplier">{{supplier.Name}}</option>
    </select>
    

    Here is an example on stackblitz.