Reputation: 93
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()"> </div>
<div class="entry value"><span>{{count}}</span></div>
<div class="entry plus" (click)="IncreaseVal()"> </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
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)"> </div>
<div class="entry value"><span>{{hero.count}}</span></div>
<div class="entry plus" (click)="IncreaseVal(hero)"> </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
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