加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 与Select / Options和ngModel / ngModelChange一起使

发布时间:2020-12-17 07:00:03 所属栏目:安全 来源:网络整理
导读:问题描述 我正在尝试使用asyncPipe和[ngModel] /(ngModelChange)使用可观察字段进行基于选择/选项的下拉列表工作.我的代码出了点问题,因为在运行时控制台会输出[object Object](请参见下图). 令我困惑的是,如果我使用[value] =“payPeriod.id”,它工作正常,
问题描述

我正在尝试使用asyncPipe和[ngModel] /(ngModelChange)使用可观察字段进行基于选择/选项的下拉列表工作.我的代码出了点问题,因为在运行时控制台会输出[object Object](请参见下图).

令我困惑的是,如果我使用[value] =“payPeriod.id”,它工作正常,并且在setSelectedPayPeriod(…)方面成功接收到数字ID.

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);
}

控制台输出

enter image description here

歉意

对不起,我对plunker不是很熟悉,也无法快速找到我可以解决的Angular 2模板.

UPD.接受的解决方案 – 由AJT_82提供

>在选项元素上使用[ngValue]而不是[value].
>在select元素上使用[ngModel] =“selectedPayPeriod | async”而不是[ngModel] =“selectedPayPeriod | json”.

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

解决方法

payPeriod是一个Object,因此如果要绑定整个对象,请使用[ngValue]而不是[value].

<option *ngFor="let payPeriod of (payPeriodList | async)" [ngValue]="payPeriod">{{ payPeriod.endDate }}</option>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读