Angular How To Conditionally Change Css Class?
Solution 1:
you can use ng class
property in angular to switch between CSS classes as an example, if I want to create a toggle button that needs to switch between the dark background and light background I can do the following changes.
HTML file
<div [ngClass]="{'black-background':blacked, 'white-background':!blacked}">
CSS / SCSS file
.black-background {
background-color: #000;
}
.white-background {
background-color: #FFF;
}
TypeScript file
In the typescript file, you need to have the property blacked
value which we pass in the HTML tag need to be true
or false
blacked = true;
for now, the blacked
value is true, so black-background
value is true
so now we can see the black background. If property blacked=false;
then the white-background
value is true
because we pass white-background:!blacked
. So like that we can toggle between the CSS classes.
Solution 2:
Use ngClass.
<mat-icon [ngClass]="{'card-icon': true, 'active-icon': currentTabElement === 'group'}">group</mat-icon>
The code above will add the card-icon
class to all icons, and the active-icon
class only when the condition currentTabElement === 'group'
evaluates to true.
Post a Comment for "Angular How To Conditionally Change Css Class?"