[javascript] Angular: conditional class with *ngClass

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

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

The answer is


While I was creating a reactive form, I had to assign 2 types of class on the button. This is how I did it:

<button type="submit" class="btn" [ngClass]="(formGroup.valid)?'btn-info':''" 
[disabled]="!formGroup.valid">Sign in</button>

When the form is valid, button has btn and btn-class (from bootstrap), otherwise just btn class.


You should use something ([ngClass] instead of *ngClass) like that:

<ol class="breadcrumb">
  <li [ngClass]="{active: step==='step1'}" (click)="step='step1; '">Step1</li>
  (...)


with the following examples you can use 'IF ELSE'

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

ngClass syntax:

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

You can use 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>
</ol>

[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">
  <div>{{item}}</div>
</template>

See also https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

<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 https://angular.io/docs/ts/latest/guide/template-syntax.html

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

In Angular 7.X

The CSS classes are updated as follows, depending on the type of the expression evaluation:

  • string - the CSS classes listed in the string (space delimited) are added

  • Array - the CSS classes declared as Array elements are added

  • Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

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

Not relevant with [ngClass] directive but I was also getting the same error as

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

and I thought to be the error in my [ngClass] condition but it turned out the property I was trying to access in the condition of [ngClass] was not initialized.

Like I had this in my typescript file

element: {type: string};

and In my [ngClass] I was using

[ngClass]="{'active', element.type === 'active'}"

and I was getting the error

Cannot read property 'type' of undefined at...

and the solution was to fix my property to

element: {type: string} = {type: 'active'};

Hope it helps somebody who is trying to match a condition of a property in [ngClass]


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

to extend MostafaMashayekhi his answer for option two> you can also chain multiple options with a ','

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

Also *ngIf can be used in some of these situations usually combined with a *ngFor

class="mats p" *ngIf="mat=='painted'"

This is what worked for me:

[ngClass]="{'active': dashboardComponent.selected_menu == 'profile'}"

Additionally, you can add with method function:

In HTML

<div [ngClass]="setClasses()">...</div>

In component.ts

// Set Dynamic Classes
  setClasses() {
    let classes = {
      constantClass: true,
      'conditional-class': this.item.id === 1
    }

    return classes;
  }

Try Like this..

Define your class with ''

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

We can make class dynamic by using following syntax. In Angular 2 plus, you can do this in various ways:

[ngClass]="{'active': arrayData.length && arrayData[0]?.booleanProperty}"
[ngClass]="{'active': step}"
[ngClass]="step== 'step1'?'active':''"
[ngClass]="step? 'active' : ''"

For elseif statement (less comparison) use like that: (For example you compare three statement)

<div [ngClass]="step === 'step1' ? 'class1' : (step === 'step2' ? 'class2' : 'class3')"> {{step}} </div>

Another solution would be using [class.active].

Example :

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

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

For Example

[ngClass]="'someClass'">

Conditional

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

Multiple Condition

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

Method expression

[ngClass]="getSomeClass()"

This method will inside of your component

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

Let, YourCondition is your condition or a boolean property, then do like this

[class.yourClass]="YourCondition"

_x000D_
_x000D_
<div class="collapse in " [ngClass]="(active_tab=='assignservice' || active_tab=='manage')?'show':''" id="collapseExampleOrganization" aria-expanded="true" style="">_x000D_
 <ul>   <li class="nav-item" [ngClass]="{'active': active_tab=='manage'}">_x000D_
<a routerLink="/main/organization/manage" (click)="activemenu('manage')"> <i class="la la-building-o"></i>_x000D_
<p>Manage</p></a></li> _x000D_
<li class="nav-item" [ngClass]="{'active': active_tab=='assignservice'}"><a routerLink="/main/organization/assignservice" (click)="activemenu('assignservice')"><i class="la la-user"></i><p>Add organization</p></a></li>_x000D_
</ul></div>
_x000D_
_x000D_
_x000D_

Code is good example of ngClass if else condition.

[ngClass]="(active_tab=='assignservice' || active_tab=='manage')?'show':''"

[ngClass]="{'active': active_tab=='assignservice'}"

You can use [ngClass] or [class.classname], both will work the same.
[class.my-class]="step==='step1'"

   OR

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

Both will work the same!


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to angular-template

How and where to use ::ng-deep? How to use *ngIf else? Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays Dynamic tabs with user-click chosen components Getting reference to child component in parent component How to use Angular2 templates with *ngFor to create a table out of nested arrays? What is the equivalent of ngShow and ngHide in Angular 2+? Angular: conditional class with *ngClass

Examples related to angular-ng-class

Angular ngClass and click event for toggling class Angular: conditional class with *ngClass