Coder Perfect

*ngClass is a conditional class in Angular.


What exactly is the issue with my Angular code? This is the error I’m getting:

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

Asked by daniel

Solution #1

There are numerous techniques to conditionally add classes in Angular 2+:

type one

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

type two

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

and multiple option:

[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'"

Answered by MostafaMashayekhi

Solution #2

instead of *ngClass, use [ngClass]=…

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

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

lieu of the more lengthy equivalent

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

See also

See also

Answered by Günter Zöchbauer

Solution #3

Another solution would be using [].

Example :

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

Answered by Joel Almeida

Solution #4

The standard structure for ngClass is as follows:

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

So, in your situation, simply utilize it as follows…

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

Answered by Alireza

Solution #5

You can use ‘IF ELSE’ in the following scenarios.

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

Answered by Chaitanya Nekkalapudi

Post is based on