Angular: conditional class with *ngClass

Angular: conditional class with *ngClass

What is wrong with my Angular code? I am getting:
Cannot read property ‘remove’ of undefined at BrowserDomAdapter.removeClass …



Solution 1:

Angular 2,..,7 provides several ways to add classes conditionally:

type one


type two

[ngClass]="{'my-class': step=='step1'}"

and multiple option:

[ngClass]="{'my-class': step=='step1', 'my-class2':step=='step2' }"

type three


type four


Solution 2:

[ngClass]=... instead of *ngClass.

* is only for the shorthand syntax for structural directives where you can for example use

<div *ngFor="let item of items">{{item}}</div>

instead of the longer equivalent version

<template ngFor let-item [ngForOf]="items">

See also

<some-element [ngClass]="'first second'">...</some-element>
<some-element [ngClass]="['first', 'second']">...</some-element>
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>

See also

<!-- toggle the "special" class on/off with a property -->
<div [class.special]="isSpecial">The class binding is special</div>

<!-- binding to `class.special` trumps the class attribute -->
<div class="special"
     [class.special]="!isSpecial">This one is not so special</div>
<!-- reset/override all class names with a binding  -->
<div class="bad curly special"
     [class]="badCurly">Bad curly</div>

Solution 3:

Another solution would be using [].

Example :

<ol class="breadcrumb">
    <li []="step=='step1'" (click)="step='step1'">Step1</li>

Solution 4:

That’s the normal structure for ngClass is:

[ngClass]="{'classname' : condition}"

So in your case, just use it like this…

<ol class="breadcrumb">
  <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>

Solution 5:

with the following examples you can use ‘IF ELSE’

<p class="{{condition ? 'checkedClass' : 'uncheckedClass'}}">
<p [ngClass]="condition ? 'checkedClass' : 'uncheckedClass'">
<p [ngClass]="[condition ? 'checkedClass' : 'uncheckedClass']">

Solution 6:

You can use ngClass to apply the class name both conditionally and not in Angular

For Example



[ngClass]="{'someClass': property1.isValid}">

Multiple Condition

 [ngClass]="{'someClass': property1.isValid && property2.isValid}">

Method expression


This method will inside of your component

        const isValid=this.property1 && this.property2;
        return {someClass1:isValid , someClass2:isValid};