Change color dynamically using ngClass or ngStyle in Angular

Issue

I would like to know how to change the color on click when we have a class defined in the css file? should we use ngClass or ngStyle?

Thanks in advance.

Css file

.text-color: {
 color:red;
}

html

<div>
 <p>
  some text...
 </p>
</div>

Solution

You can just bind to the HTML property instead:

<div (click)="divClicked = !divClicked">
 <p [class.text-color]="divClicked">
  some text...
 </p>
</div>

in your component, create the class property to track the state of the click:

divClicked = false

Stackblitz

Answered By – Meqwz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published