HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptangularCritical

Angular: conditional class with *ngClass

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
angularwithconditionalngclassclass

Problem

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

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


Step1
Step2
Step3

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.

Code Snippets

[class.my_class] = "step === 'step1'"
[ngClass]="{'my_class': step === 'step1'}"
[ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"
[ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"
[ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"

Context

Stack Overflow Q#35269179, score: 2813

Revisions (0)

No revisions yet.