【问题标题】:Event triggers on multiple elements instead one in *ngFor多个元素上的事件触发,而不是 *ngFor 中的一个
【发布时间】: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


    【解决方案1】:

    我希望每个项目都有自己的 qnt 属性 您的递增/递减函数也可以传入您想要操作的相应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;
     }
    

    【讨论】:

    • 没有任何改变,控制台中没有显示任何内容。我只是放了 console.log 函数来测试行为,它可以工作,但是增量/减量函数既不工作也不调用控制台中的任何错误。
    • 我必须在我的 json 对象中添加属性 qnt(我想在开始时添加它)并且一切正常
    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 2014-06-10
    • 1970-01-01
    • 2017-04-25
    相关资源
    最近更新 更多