I'm using Mat-card to display a list using an array and *ngFor and when pressed on the button, it will change the icon (mat-icon) only on the selected card but it changes for all the buttons in the list.
here's an example:
it's before pressing on the button and the condition to change the icon is false
but when I press it all the icons change.
here's my code:
<mat-card *ngFor="let a of items ;let i = index" class="item-card mat-card">
<mat-card-header class="card-mat-header" style="margin-top: 10px;">
<div class="card-mat-header-text"></div>
<mat-card-title class="card-mat-title">{{a.name}}</mat-card-title>
<mat-card-subtitle>Price :{{a.price}}</mat-card-subtitle>
</mat-card-header>
<div class="img-wrapper">
<img class="mat-card-image" src={{a.image}} alt="Photo of a Shiba Inu">
</div>
<mat-card-content>
<p>
{{a.desc}}
</p>
</mat-card-content>
<mat-card-actions class="right-button" >
<button mat-button class="mat-button mat-button-base" (click)="itemStatus(i)" >
<mat-icon>{{iconName}}</mat-icon>{{itemStatis}} {{a.addedToCart}}
</button>
</mat-card-actions>
</mat-card>
also the used function:
itemStatus(i){
this.items[i].addedToCart = !this.items[i].addedToCart
if(this.items[i].addedToCart)
{
this.iconName = "shopping_cart";
this.itemStatis= "Added";
}
else{
this.iconName = "add_shopping_cart";
this.itemStatis= "Add To Cart";
}
}
please if anyone is familiar with this kind of mistake help me.
You are maintaining the iconName
and itemStatis
at component level not at the item
level
Check the Example below
https://stackblitz.com/edit/angular-ivy-moun8k
In XComponent.ts change itemStatus
to
itemStatus(i){
this.items[i].addedToCart = !this.items[i].addedToCart
}
In HTML change Button section to
<button mat-button class="mat-button mat-button-base" (click)="itemStatus(i)" >
<mat-icon>{{a.addedToCart ? 'shopping_cart' : 'add_shopping_cart'}}</mat-icon>
{{a.addedToCart ? 'Added' : 'Add To Cart'}}
</button>