Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda