【发布时间】:2017-02-14 05:26:05
【问题描述】:
在我的 Angular2 应用程序中,我有以下 'view' 代码:
<ul class="cart">
<li *ngFor="let item of cartService.cart$ | async">//BehaviorSubject
<h3 class="title">{{item.title}}</h3>
<span class="descr">{{item.description}}</span>
<button (click)="decrQnt()">-</button>
<form action="#">
<input type="text" maxlength="3" id="qnt" readonly="readonly" value="{{qnt}}">
</form>
<button (click)="incrQnt()">+</button>
</li>
</ul>
在component.ts中:
public qnt: number = 1;
incrQnt(){
this.qnt < 100 ? ++this.qnt : 0;
}
decrQnt(){
this.qnt > 1 ? this.qnt-- : 0;
}
问题是我的函数同时适用于由 *ngFor 创建的视图中的所有元素,当然,我需要增加/减少单击按钮的元素的数量。
我试图将 'item' 作为参数传递给触发函数,但后来 AppComponent 类型上不存在属性 'item'
在视图中尝试将 {{qnt}} 更改为 {{item.qnt}} 并得到 Can't read property qnt of undefined
我猜是因为使用了 BehaviorSubject,因为其他属性如 item.description 和 item.title 是通过 json 传递的,而 qnt 是在运行时初始化的。
但是现在该怎么处理呢?
【问题讨论】:
标签: angular typescript ngfor behaviorsubject