Search code examples
angulartypescriptngforbehaviorsubject

Event triggers on multiple elements instead one in *ngFor


In my Angular2 app I've got following code for the '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>

In component.ts:

public qnt: number = 1;

incrQnt(){
   this.qnt < 100 ? ++this.qnt : 0;
}

decrQnt(){
    this.qnt > 1 ? this.qnt-- : 0;
 }

The problem is that my functions work simultaneously for all elements in my view created by *ngFor And I need, of course, to increment / decrement quantity of only one element which button is clicked.

I tried to pass 'item' as an argument to the trigger functions, but then I had Property 'item' does not exist on type AppComponent

In the view tried to change {{qnt}} to {{item.qnt}} and got Can't read property qnt of undefined

I guess it's because of using BehaviorSubject, because other properties such as item.description and item.title are passed via json, while qnt is initialized on the run.

But how to deal with it now?


Solution

  • I expect each item ahs its own qnt property Your increment/decrement function could also pass in the respective item you want the operation on

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