3

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?

B45i
  • 2,368
  • 2
  • 23
  • 33
Frank Jusnes
  • 175
  • 1
  • 13

2 Answers2

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

B45i
  • 2,368
  • 2
  • 23
  • 33
  • Thanks for replying, B45i! What I am looking for is how I can create a model (as an observable) for the selected value. The model has the last supplier in the list as an initial value. And regarding the empty element, is there a way to add it to the supplier list observable instead of just adding a static one? – Frank Jusnes Apr 24 '20 at 15:17
  • 1
    @frank-jusnes Created an example for you in stackblitz: https://stackblitz.com/edit/stackoverflow-61411044. I tried to use variable name that you used, but had to change it in few places as i don't have access to the exact API. – B45i Apr 24 '20 at 15:33
2
  1. Use ReactiveForms FormControl on the select input
<select [formControl]="selectedSupplier">
  <option *ngFor="let supplier of supplierList$ | async" [ngValue]="supplier"
    >{{supplier.name}}</option
  >
</select>

And use the setValue function on the FormControl to set the initial value from the observable in a tap pipe function

selectedSupplier = new FormControl();

this.mySupplierList$ = this._mySupplierService.getSupplierList()
.pipe(
  tap((suppliers)=> {
    this.selectedSupplier.setValue(suppliers[suppliers.length - 1]);
  })
);
  1. Manipulate the data in the observable using the RxJs map function. Add an object to the array using the Javascript array unshift function.
this.mySupplierList$ = this._mySupplierService.getSupplierList()
.pipe(
  map((suppliers)=> {
    suppliers.unshift({ id: null, name: "Select" });
    return suppliers;
  })
);

Stackblitz with both the solutions

Dmitry S.
  • 1,544
  • 2
  • 13
  • 22
C J
  • 46
  • 5