I am currently working on setting up a voting feature where the active vote is highlighted with a blue background. To achieve this, I am using 2 boolean variables to track the score and the selected option. While attempting to use NgClass, I encountered some difficulty in understanding how it functions in my specific scenario as I need to add an extra class to the existing 2 classes.
Styling (CSS)
.voting {
cursor: pointer;
display: inline;
}
.activeVote {
background: #2980b9;
}
HTML Code
The 'voting' class and 'noSelect' class should always remain active. However, when clicking on 'increaseUpvote()', the 'activeVote' class should be added to indicate that the upvoted boolean is true. The same behavior should apply to the downvote option.
<p style="font-size: 28px;">{{post.upvotes}}
<mat-icon class="voting noSelect" (click)="increaseUpvote()">arrow_upward
</mat-icon>
<mat-icon class="voting noSelect" (click)="increaseDownvote()">
arrow_downward
</mat-icon>
</p>
Typescript Code
public upvoted: boolean = false;
public downvoted: boolean = false;
increaseUpvote(): void {
if (this.downvoted) {
this.post.upvote();
this.downvoted = false;
}
if (!this.upvoted) {
this.post.upvote();
this.upvoted = true;
} else if (this.upvoted) {
this.post.removeUpvote();
this.upvoted = false;
}
}
increaseDownvote(): void {
if (this.upvoted) {
this.post.removeUpvote();
this.upvoted = false;
}
if (!this.downvoted) {
this.post.removeUpvote();
this.downvoted = true;
} else if (this.downvoted) {
this.post.upvote();
this.downvoted = false;
}
}