Varadha Raj
Varadha Raj

Reputation: 93

Angular 4 *ngFor current element value to increase and decrease

I'm making a little application in Angular 4, I'm displaying a table with some data, I wanna increase and decrease the current value by clicking DecreaseVal() and IncreaseVal() function, but it change all the value in the loop.

<tr class="rem1" *ngFor="let hero of heroes">
   <td class="invert">
    <div class="quantity">
        <div class="quantity-select">
            <div class="entry minus" (click)="DecreaseVal()">&nbsp</div>
            <div class="entry value"><span>{{count}}</span></div>
            <div class="entry plus" (click)="IncreaseVal()">&nbsp;</div>
        </div>
    </div>
  </td>
</tr>

This is my component

 count=1;
    DecreaseVal()
    {
    this.count=this.count>1?this.count-1:this.count;
    }
    IncreaseVal()
    {
     this.count=this.count<5?this.count+1:this.count;
    }

Upvotes: 1

Views: 2141

Answers (2)

Vitalii Chmovzh
Vitalii Chmovzh

Reputation: 2943

It happens because your count variable is global and doesn't belong to the Hero class. You need to tweak you code in the following way:

Declare new field in hero.class.ts

count: number = 0;

Tweak your template component.html

<tr class="rem1" *ngFor="let hero of heroes">
   <td class="invert">
    <div class="quantity">
        <div class="quantity-select">
            <div class="entry minus" (click)="DecreaseVal(hero)">&nbsp</div>
            <div class="entry value"><span>{{hero.count}}</span></div>
            <div class="entry plus" (click)="IncreaseVal(hero)">&nbsp;</div>
        </div>
    </div>
  </td>
</tr>

And now in component.ts

DecreaseVal(hero: Hero)
{
    if (hero.count > 1) {
       hero.count--;
    }
}

IncreaseVal(hero: Hero)
{
    if (hero.count < 5) {
       hero.count++;
    }
}

UPD: Updated with suggestions and notes from Andrien Brunelat.

Upvotes: 1

Jordy Garc&#237;a
Jordy Garc&#237;a

Reputation: 141

There are two possible solutions for your problem. First of all, it will increase all the values because is the same variable for all elements you are iterating. The first and quick solution is to add that count to your heroe object in your heroes array. Something like

heroes = [{heroName:'example', count : 0}, {heroName:'other', count : 0}];

Then, in your event you have to send the index to make the method know where to increase.

(click)="IncreaseVal(i)"

In your component then you have to increase the counter of that object.

IncreaseVal(index){ this.heroes[index].count++; }

The other solution is to create a child component for heroes. It will have the completed td and the counter val.

Upvotes: 2

Related Questions