最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2 [attr.class] overwrites native DOM classes - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Oct 8, 2017 at 7:26 Cœur 38.8k25 gold badges205 silver badges277 bronze badges asked Jul 16, 2016 at 11:49 Pho HuynhPho Huynh 1,5773 gold badges13 silver badges23 bronze badges 3
  • 2 You could use ngClass directive find it here – Pankaj Parkar Commented Jul 16, 2016 at 12:07
  • @PankajParkar Wow, I don't even know we can use ngClass instead of [ngClass]. Can you explain what is the different? – Pho Huynh Commented Jul 16, 2016 at 12:13
  • 2 There is no difference. The [] is for all attribute and property bindings, not only for ngClass – Günter Zöchbauer Commented Jul 16, 2016 at 12:22
Add a ment  | 

2 Answers 2

Reset to default 4

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.

[attr.class]='classNameB'

here the classNameB should be $scope attached variable. which can be an expression or value. you can also modify the code like this

[attr.class]='{{getClassName()}}'

for ng-class attribute it works same for both. or you can have a class on boolean basis

[attr.class]="'ifThis'?'classNameB':'classNameA'"

or

 ng-class="varA==0 ?'classNameB':'classNameA'"
发布评论

评论列表(0)

  1. 暂无评论