0

I have an icon with a default class , the class name is card-icon , now how do I change the class based on condition or disable the class ?

Because the default color of the icon is gray now when condition is met or condition true I want to change it to black color.

The condition is below , when condition is true disable class="card-icon" or if it is not possible to disable then replace when a new class for example [class.newclass] .

Any idea how to implement this guys ? Thank you.

#Icon with default class

 <mat-icon class="card-icon">group</mat-icon>

#Condition

<mat-icon class="active-icon" [class.newclass]="currentTabElement === 'group'">group</mat-icon>

2 Answers2

5

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.

0

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.

nip
  • 1,609
  • 10
  • 20
  • I tried the above implementation Sir , but it does not work [ngClass]="{'card-icon': true, 'active-icon': currentTabElement === 'group'}" –  Jul 25 '21 at 15:43
  • @TimLaunders there was a missing closing bracket, I've edited the code. I was able to run this locally, are you sure the condition is correct ? Do you see the `active-icon` class being added when the condition evaluates to `true` ? – nip Jul 25 '21 at 16:31