Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
Change color dynamically using ngClass or ngStyle in Angular

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>
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

codeSolution:https://stackblitz.com/edit/ngstyle-examples-m7sifc?file=src/app/app.component.html

html

<p [ngStyle]="{ color: colorFlag }">top</p>
<button (click)="change()">click</button>

ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  colorFlag = 'red';
  change(){
  this.colorFlag= 'green';
  }
}

explination: onclick of button color of p tag will change to green , by default it will be red

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

If you are using class, compliant solution:

<div
  <p [ngClass]="{'text-red': true, 'text-white': false}"> 
    some text...
  </p>
</div>

with class on your css file

.text-red: { 
   color:red;
}
.text-white: { 
   color:white;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!