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>
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
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
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;
}