首页 > 解决方案 > 如何动态添加一个类?

问题描述

我已经在 Angular 中编程了很短的时间,但我被困在按钮设计上。我已经用 ngIf 实现了它们,根据它们是否可用动态地出现和消失。问题是我觉得它有点复杂,我想利用相同的逻辑让它们始终显示在屏幕上,但根据我之前使用的相同条件添加颜色。我试图实现 ngClass 的使用,但很明显有些地方是错误的,因为它不起作用。这是我的html:

<div *ngIf="mainFlowchartInstance.eisChartData.value" class="temp_zoom-actions">
      <div [ngClass]="{'orangeText' : zoomButtons == 'zoomButtons.reset'}" class="center" (click)="zoomReset()"><i class="icon-refresh"></i></div>
      <div [ngClass]="{'orangeText' : zoomButtons == 'zoomButtons.out'}" class="zoom-out" (click)="zoomOut()"><i class="icon-search-minus"></i></div>
      <div [ngClass]="{'orangeText' : zoomButtons == 'zoomButtons.in'}" class="zoom-in" (click)="zoomIn()"><i class="icon-search-plus"></i></div>
</div>    

这里是我的 ts:

  public zoomButtons = {
    in: false,
    out: true,
    reset: false
  };


  setZoomButtonsState() {
    this.zoomButtons.out = !!this.currentZoomPosition;
    this.zoomButtons.in = this.zoomButtons.reset = !(this.currentZoomPosition === this.rangeZooms.length - 1);
  }

有人让我看到我的错误吗?先感谢您。

标签: angulardynamicangular7ng-class

解决方案


尝试以这种方式使用它(检查 if zoomButtons.resetor zoomButtons.outor zoomButtons.inare trueor false,然后应用 class orangeText):

<div [ngClass]="{'orangeText' : zoomButtons.reset}" 
  class="center" (click)="zoomReset()">
  <i class="icon-refresh"></i>
</div>
<div [ngClass]="{'orangeText' : zoomButtons.out}" 
  class="zoom-out" (click)="zoomOut()">
  <i class="icon-search-minus"></i>
</div>
<div [ngClass]="{'orangeText' : zoomButtons.in}" 
  class="zoom-in" (click)="zoomIn()">
  <i class="icon-search-plus"></i>
</div>

orangeText将应用,如果它得到true之后:,就像在这个例子中的角度文档

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">  

在这个地方:

[ngClass]="{'orangeText' : zoomButtons.reset}"

zoomButtons.reset没有单引号将被视为变量,因此将返回trueor false


推荐阅读