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>
4
  • 1
    Isn't this a duplicate of stackoverflow.com/questions/35269179/… Commented Jul 25, 2021 at 15:39
  • I think No Sir ,. Commented Jul 25, 2021 at 15:43
  • I mean it's basically the same thing. With that information in mind you can build your own solution. And welcome to StackOverflow, anyway! Commented Jul 25, 2021 at 15:54
  • Does this answer your question? Angular: conditional class with *ngClass Commented Jul 25, 2021 at 16:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

I tried the above implementation Sir , but it does not work [ngClass]="{'card-icon': true, 'active-icon': currentTabElement === 'group'}"
@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 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.