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);
}
Sorry, I'm not very familiar with plunker and can't quickly find an Angular 2 template I can work off.
[ngValue]
instead of [value]
on option
element.[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>
To get the asynchronous flow data, we can use the subscribe method to subscribe to the observables, or we can simply use async pipe , which automatically subscribes to an observable and returns the latest value. It also unsubscribes automatically to avoid memory leaks.
Angular's async pipe is a pipe that subscribes to an Observable or Promise for you and returns the last value that was emitted. $observable. subscribe((result) => { // do something with the result here }); Every time a new value is emitted the async pipe will automatically mark your component to be checked for changes.
The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.
payPeriod
is an Object, so if you want to bind the whole object, use [ngValue]
instead of [value]
.
<option *ngFor="let payPeriod of (payPeriodList | async)" [ngValue]="payPeriod">{{ payPeriod.endDate }}</option>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With