角度点击切换当前元素的书签图标样式



正在尝试在单击时切换当前元素的书签图标颜色,但它已应用于所有书签图标

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

谢谢

这是因为您为每个项目都使用了单个变量。为数组中的每个项目创建一个状态键products(示例如下所示(

<button mat-icon-button (click)="product.status = !product.status" style="float: right;">
<mat-icon [ngClass]="product.status ? 'bookmark' : 'bookmarked'">favorite</mat-icon>
</button>

试试这种方式

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>

您可以使用条件类来实现此目的

首先创建自己的类,然后

[class.yourclass]="condition">

更多参考角度:带有 *ngClass 的条件类

最新更新