0

am trying toggle bookmark icon color for current element onclick but it's getting applied to all the bookmark icons

<div *ngFor="let product of products">
    <mat-card class="col-md-3">
        <img style="height:100%; width: 100%;" src="{{ product.imageUrl }}" />
        <div class="card-body">
            <mat-card-title>{{product.name}}</mat-card-title>
            <mat-card-content>
                <p>{{product.description}}</p>
            </mat-card-content>
            <mat-card-subtitle>&#8377; {{product.price}}</mat-card-subtitle>
            <mat-card-actions>
                <button mat-flat-button color="primary" style="margin-right: 7px;"> Add to Bag </button>
                <button mat-icon-button aria-label="Example icon-button with a heart icon"
                    (click)="clickEvent($event)" style="float: right;">
                    <mat-icon [ngClass]="status ? 'bookmark' : 'bookmarked'">favorite</mat-icon>
                </button>
            </mat-card-actions>
        </div>
    </mat-card>
</div>

TS

status: boolean = false;
private clickEvent() {
    this.status = !this.status;
}

thanks

Bobby
  • 89
  • 1
  • 2
  • 13

3 Answers3

3

Thats because you used a single variable for every item. Create a status key for each item in products array (Example shown below)

<button mat-icon-button (click)="product.status = !product.status" style="float: right;">
  <mat-icon [ngClass]="product.status ? 'bookmark' : 'bookmarked'">favorite</mat-icon>
</button>
Sameer
  • 4,758
  • 3
  • 20
  • 41
0

Try this way

private clickEvent(event, index) {
    this.products[index].status = ! this.products[index].status;
}
<div *ngFor="let product of products;let i = index">
        <mat-card class="col-md-3">
            <img style="height:100%; width: 100%;" src="{{ product.imageUrl }}" />
            <div class="card-body">
                <mat-card-title>{{product.name}}</mat-card-title>
                <mat-card-content>
                    <p>{{product.description}}</p>
                </mat-card-content>
                <mat-card-subtitle>&#8377; {{product.price}}</mat-card-subtitle>
                <mat-card-actions>
                    <button mat-flat-button color="primary" style="margin-right: 7px;"> Add to Bag </button>
                    <button mat-icon-button aria-label="Example icon-button with a heart icon"
                        (click)="clickEvent($event,index)" style="float: right;">
                        <mat-icon [ngClass]="status ? 'bookmark' : 'bookmarked'" instead of
                            [ngClass]="status ? 'bookmark' : 'bookmarked'">favorite</mat-icon>
                    </button>
                </mat-card-actions>
            </div>
        </mat-card>
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
0

You can achieved this using conditional classes

first create your own class and then

[class.yourclass]="condition"

for more ref Angular: conditional class with *ngClass