Angular 6: Additional class if boolean is true
Asked Answered
I

1

5

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;
    }
  }
Ibnrushd answered 6/5, 2019 at 19:29 Comment(0)
S
7

I think what you are looking for is included in Angular's basic template syntax.

this will add the class "activeVote" if "upvoted" is true

<div [class.activeVote]="upvoted">

and this will add class "activeVote" if "upvoted" is false

<div [class.activeVote]="!upvoted">

for more reference https://angular.io/guide/template-syntax#binding-targets

Stirpiculture answered 6/5, 2019 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.