事件在多个元素上触发,而不是 *ngFor 中的一个
Event triggers on multiple elements instead one in *ngFor
在我的 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' 作为参数传递给触发器函数,但后来我发现 属性 'item' 在类型 AppComponent[=34 上不存在=]
在视图中尝试将 {{qnt}} 更改为 {{item.qnt}} 并得到 无法读取 属性 未定义的 qnt
我猜是因为使用了BehaviorSubject,因为其他属性如item.description和item.title是通过json传递的,而qnt是在运行上初始化的。
但是现在怎么处理呢?
我希望每个项目都有自己的 qnt
属性
您的 increment/decrement 函数还可以传入您希望在
上进行操作的相应 item
<button (click)="decrQnt(item)">-</button>
<button (click)="incrQnt(item)">+</button>
incrQnt(item){
item.qnt < 100 ? ++item.qnt : 0;
}
decrQnt(item){
item.qnt > 1 ? item.qnt-- : 0;
}
在我的 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' 作为参数传递给触发器函数,但后来我发现 属性 'item' 在类型 AppComponent[=34 上不存在=]
在视图中尝试将 {{qnt}} 更改为 {{item.qnt}} 并得到 无法读取 属性 未定义的 qnt
我猜是因为使用了BehaviorSubject,因为其他属性如item.description和item.title是通过json传递的,而qnt是在运行上初始化的。
但是现在怎么处理呢?
我希望每个项目都有自己的 qnt
属性
您的 increment/decrement 函数还可以传入您希望在
item
<button (click)="decrQnt(item)">-</button>
<button (click)="incrQnt(item)">+</button>
incrQnt(item){
item.qnt < 100 ? ++item.qnt : 0;
}
decrQnt(item){
item.qnt > 1 ? item.qnt-- : 0;
}