Search code examples
javascriptcssangularangular-templateangular-ng-class

Angular: conditional class with *ngClass


What is wrong with my Angular code? I am getting the following error:

Cannot read property 'remove' of undefined at BrowserDomAdapter.removeClass

<ol>
  <li *ngClass="{active: step==='step1'}" (click)="step='step1'">Step1</li>
  <li *ngClass="{active: step==='step2'}" (click)="step='step2'">Step2</li>
  <li *ngClass="{active: step==='step3'}" (click)="step='step3'">Step3</li>
</ol>

Solution

  • Angular version 2+ provides several ways to add classes conditionally:

    Type one

        [class.my_class] = "step === 'step1'"
    

    Type two

        [ngClass]="{'my_class': step === 'step1'}"
    

    and multiple options:

        [ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"
    

    Type three

        [ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"
    

    Type four

        [ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"
    

    You can find these examples on the the documentation page.