Is there a way to add a class from the .ts file, using Angular solutions
<div [class.extra-sparkle]="isDelightful == true">
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>
I would like to just add something like this into the ChangeScreen function:
ChangeScreen(page) {
page.addClass = page;
}
Then I can remove all of those lines: [class.selected]="CurrentPage == '...'"
To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.
In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript.
You can use ngClass
directive:
<div id="mydiv" [ngClass]="{'myCSSclass' : condition}"></div>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With