Angular 6:附加 class 如果 boolean 为真

Angular 6: Additional class if boolean is true

我正在尝试实现一个投票系统,其中主动投票的背景为蓝色。为此,我使用 2 个布尔值来跟踪分数和所选选项。我尝试使用 NgClass,但我似乎无法弄清楚它在我的案例中是如何工作的,因为我要在现有的 2 class 中添加一个额外的 class。

css

 .voting{
    cursor: pointer; 
    display: inline;
  }
  .activeVote{
    background: #2980b9;
  }

HTML

voting class 和 noSelect 应该始终处于活动状态,但是单击 increaseUpvote() 应该将 activeVote class 添加到那个,因为 upvoted 布尔值将为真。 downvote 选项也应该发生同样的事情。

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

打字稿

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

我认为您正在寻找的内容包含在 Angular 的基本模板语法中。

这将添加 class "activeVote" 如果 "upvoted" 为真

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

如果 "upvoted" 为假,这将添加 class "activeVote"

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

更多参考https://angular.io/guide/template-syntax#binding-targets