与Select/Options&一起使用的异步管道ngModel/ngModelChange [英] Async Pipe used with Select/Options & ngModel/ngModelChange
问题描述
我正在尝试使用asyncPipe
和[ngModel]
/(ngModelChange)
使用可观察字段来进行基于select
/option
的下拉菜单.我的代码出了点问题,因为在运行时控制台输出[object Object]
(请参见下图).
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).
让我感到困惑的是,如果我使用[value]="payPeriod.id"
,它可以正常工作,并且在setSelectedPayPeriod(...)
端成功接收到数字id
.
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);
}
控制台输出
对不起,我对plunker不太熟悉,无法快速找到我可以使用的Angular 2模板.
Sorry, I'm not very familiar with plunker and can't quickly find an Angular 2 template I can work off.
- 在
option
元素上使用[ngValue]
代替[value]
. - 在
select
元素上使用[ngModel]="selectedPayPeriod | async"
代替[ngModel]="selectedPayPeriod | json"
.
- Use
[ngValue]
instead of[value]
onoption
element. - Use
[ngModel]="selectedPayPeriod | async"
instead of[ngModel]="selectedPayPeriod | json"
onselect
element.
<select [ngModel]="selectedPayPeriod | async" (ngModelChange)="setSelectedPayPeriod($event)">
<option *ngFor="let payPeriod of (payPeriodList | async)" [ngValue]="payPeriod">{{ payPeriod.endDate }}</option>
</select>
推荐答案
payPeriod
是一个对象,因此,如果要绑定整个对象,请使用[ngValue]
而不是[value]
.
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>
这篇关于与Select/Options&一起使用的异步管道ngModel/ngModelChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!