javascript - Change color dynamically using ngClass or ngStyle in Angular - Stack Overflow

I would like to know how to change the color on click when we have a class defined in the css file? sho

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), and ngStyle changes CSS directly inline. – Jeremy Thille Commented Sep 20, 2021 at 15:45
Add a ment  | 

3 Answers 3

Reset to default 2

You 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信