Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular add class dynamically

Tags:

html

css

angular

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 == '...'"

like image 799
Paul Kruger Avatar asked Jul 05 '18 09:07

Paul Kruger


People also ask

How do I add a class in angular 10?

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.

How do you apply dynamic class to an element?

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.


1 Answers

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.

like image 55
sticky_elbows Avatar answered Oct 06 '22 07:10

sticky_elbows