Async Pipe used with Select/Options & ngModel/ngModelChange

Viewed 17023

Problem Description

I am trying to make a select/option-based dropdown work with an observable fields using asyncPipe and [ngModel]/(ngModelChange). Something is very wrong with my code because in run time the console outputs an [object Object] (please see image below).

What confuses me is that if I use [value]="payPeriod.id", it works fine and the numeric id is successfully received on setSelectedPayPeriod(...) side.

component.html

  <select [ngModel]="selectedPayPeriod | json" (ngModelChange)="setSelectedPayPeriod($event)">
    <option *ngFor="let payPeriod of (payPeriodList | async)" [value]="payPeriod">{{ payPeriod.endDate }}</option>
  </select>

component.ts

get payPeriodList(): Observable<PayPeriod[]> {
  return this._contextService.payPeriodList;
}

get selectedPayPeriod(): Observable<PayPeriod> {
  return this._contextService.selectedPayPeriod;
}

setSelectedPayPeriod(newValue: PayPeriod): void {
  console.warn(newValue);
  this._contextService.setSelectedPayPeriod(newValue);
}

Console output

enter image description here

Apology

Sorry, I'm not very familiar with plunker and can't quickly find an Angular 2 template I can work off.

UPD. Accepted Solution -- by AJT_82

  1. Use [ngValue] instead of [value] on option element.
  2. Use [ngModel]="selectedPayPeriod | async" instead of [ngModel]="selectedPayPeriod | json" on select element.

  <select [ngModel]="selectedPayPeriod | async" (ngModelChange)="setSelectedPayPeriod($event)">
    <option *ngFor="let payPeriod of (payPeriodList | async)" [ngValue]="payPeriod">{{ payPeriod.endDate }}</option>
  </select>
1 Answers
Related