Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda