角动态添加类 [英] Angular add class dynamically
本文介绍了角动态添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种使用Angular解决方案从.ts文件中添加类的方法
Is there a way to add a class from the .ts file, using Angular solutions
<div [class.extra-sparkle]="isDelightful == true">
我想从.ts文件的侧面进行上述操作.代码越少越好.
I want to do the above but from the side of the .ts file. The less code the better.
<button class="general" (click)="ChangeScreen('Global')" [class.selected]="CurrentPage == 'Global'">Global</button>
<button class="general" (click)="ChangeScreen('Maintenance')" [class.selected]="CurrentPage == 'Maintenance'">Maintenance</button>
<button class="general" (click)="ChangeScreen('Settings')" [class.selected]="CurrentPage == 'Settings'">Settings</button>
<button class="general" (click)="ChangeScreen('Profile')" [class.selected]="CurrentPage == 'Profile'">Profile</button>
<button class="general" (click)="ChangeScreen('Transactions')" [class.selected]="CurrentPage == 'Transactions'">Transactions</button>
我只想在ChangeScreen函数中添加以下内容:
I would like to just add something like this into the ChangeScreen function:
ChangeScreen(page) {
page.addClass = page;
}
然后我可以删除所有这些行:[class.selected]="CurrentPage == '...'"
Then I can remove all of those lines: [class.selected]="CurrentPage == '...'"
推荐答案
您可以使用ngClass
指令:
<div id="mydiv" [ngClass]="{'myCSSclass' : condition}"></div>
就这么简单!仅当condition
评估为true
时,myDiv才具有类myCSSclass
.可以在您的打字稿文件或模板中设置此条件.
Simple as that! myDiv will have the class myCSSclass
only when the condition
evaluates to true
. This condition can be set in your typescript file or in the template.
这篇关于角动态添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文