Search code examples
angulardynamicangular7ng-class

how to add a class dynamically?


I've been programming in Angular for a short time and I got stuck on the button design. I have already implemented them with an ngIf, appearing and disappearing dynamically depending on whether they were available or not. The thing is that I find it a bit complicated and I wanted to take advantage of the same logic to have them always displayed on screen but add color depending on the same condition that I used before. I have tried to implement the use of ngClass but it is clear that something is wrong because it does not work. here my 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>    

and here my 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);
  }

Someone to make me see my mistake? Thank you in advance.


Solution

  • Try to use it in this way (check if zoomButtons.reset or zoomButtons.out or zoomButtons.in are true or false, then apply 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>
    

    Class orangeText will apply if it gets true after :, like in this example from angular doc:

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

    and in this place:

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

    zoomButtons.reset without single quotation marks will be treated as a variable, so will return true or false.