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>
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>
Share
edited Sep 20, 2021 at 15:44
R. Richards
25.2k10 gold badges66 silver badges65 bronze badges
asked Sep 20, 2021 at 15:38
HergeHerge
591 silver badge11 bronze badges
1
-
Either would work.
ngClass
changes a class (to which you can apply CSS), andngStyle
changes CSS directly inline. – Jeremy Thille Commented Sep 20, 2021 at 15:45
3 Answers
Reset to default 2You can just bind to the HTML property instead:
<div (click)="divClicked = !divClicked">
<p [class.text-color]="divClicked">
some text...
</p>
</div>
in your ponent, create the class property to track the state of the click:
divClicked = false
Stackblitz
codeSolution:https://stackblitz./edit/ngstyle-examples-m7sifc?file=src/app/app.ponent.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.ponent.html',
styleUrls: ['./app.ponent.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
If you are using class, pliant 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;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745074200a4609735.html
评论列表(0条)