I'm trying to implement a voting system, where the active vote gets a blue background. For this I'm using 2 booleans to keep track of the score and the selected option. I tried using NgClass, but I can't seem to figure out how it works in my case, since I'd add an additional class to the existing 2 classes.
css
.voting{
cursor: pointer;
display: inline;
}
.activeVote{
background: #2980b9;
}
HTML
voting class and noSelect should always be active, but clicking increaseUpvote() should add the activeVote class to that one since the upvoted boolean will be true. Same thing should happen 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
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;
}
}