admin管理员组文章数量:1384663
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?
-
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 forngClass
– Günter Zöchbauer Commented Jul 16, 2016 at 12:22
2 Answers
Reset to default 4So 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'"
本文标签: javascriptAngular 2 attrclass overwrites native DOM classesStack Overflow
版权声明:本文标题:javascript - Angular 2 [attr.class] overwrites native DOM classes - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744483554a2608312.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论