与Select/Options&一起使用的异步管道ngModel/ngModelChange [英] Async Pipe used with Select/Options & ngModel/ngModelChange

查看:84
本文介绍了与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.

  1. option元素上使用[ngValue]代替[value].
  2. select元素上使用[ngModel]="selectedPayPeriod | async"代替[ngModel]="selectedPayPeriod | json".
  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>

推荐答案

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&amp;一起使用的异步管道ngModel/ngModelChange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆