Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 [attr.class] overwrites native DOM classes

Tags:

I have a variable holding my class name string:

classNameB = "class-B";

I want to add this class name to a native DOM element via [attr.class]:

<div class="class-A" [attr.class]='classNameB'></div>

Then, angular overwrites the current DOM class class-A. What has left after element created is something like:

<div class="class-B"></div>

What am I doing wrong here and how to work around on this?

PS: Can I use [ngClass] instead and how?

like image 954
Pho Huynh Avatar asked Jul 16 '16 11:07

Pho Huynh


1 Answers

So I went through some funny situations where I almost ran out of options. Most of the time, I use [ngClass] and it was fine until:

<div class='native-class' [ngClass]='classNameHolder' [ngClass]='{"some-class": isSomeClass}'>

where,

classNameHolder: string = 'class-name-1';
isSomeClass: boolean = true;

I was stuck until I find good use of ngClass:

<div class='native-class' ngClass='{{classNameHolder}} {{isSomeClass ? "some-class" : ""}}></div>

And that's it. This is final option that I've been using from then. Hope it'll help if anyone runs into the same sitation.

like image 111
Pho Huynh Avatar answered Oct 03 '22 02:10

Pho Huynh