I'm trying to change a style and increment a favorites count, the problem is my code changes the style for all heart elements. I've tried using index like favClicked === i
but then when you click on another heart, it disables the style from the previous click.
My code:
<td mat-cell *matCellDef="let item; let i = index" class="favorite">
<mat-icon
(click)="showRed = true; increment(showRed)"
*ngIf="!showRed"
>favorite</mat-icon
>
<mat-icon
(click)="showRed = false; increment(showRed)"
class="red"
*ngIf="showRed"
>favorite</mat-icon
>
</td>
...
increment(showRed: boolean) {
console.log(showRed);
if (showRed) {
this.childComponent.incrementCount();
} else {
this.childComponent.decrementCount();
}
}
Screenshot of the problem; you can see it changes the styling for all the hearts on click of the top heart, which originally was black color and changes to red on click.
I used item.clicked
which uses the item iteration, which targeted the table cell click of the heart. Then I reverse the boolean on click item.clicked = !item.clicked;
, use [ngClass]="{ red: item.clicked }"
to select the red class if true. Then increment in the method.
<td mat-cell *matCellDef="let item; let i = index" class="favorite">
<mat-icon (click)="item.clicked = !item.clicked; increment(item.clicked, item, i)"
ngClass]="{ red: item.clicked }">favorite</mat-icon>
</td>
...
increment(item: boolean) {
if (item) {
this.childComponent.incrementCount();
} else {
this.childComponent.decrementCount();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.