在Angular中使用ngClass或ngStyle动态更改颜色



我想知道如何改变颜色点击时,我们有一个类定义在css文件?我们应该使用ngClass还是ngStyle?

提前感谢。

Css文件

.text-color: {
color:red;
}

<div>
<p>
some text...
</p>
</div>

你可以直接绑定到HTML属性:

<div (click)="divClicked = !divClicked">
<p [class.text-color]="divClicked">
some text...
</p>
</div>

中,创建class属性来跟踪单击的状态:

divClicked = false

Stackblitz

cosoluution: 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:点击按钮后,p标签的颜色变为绿色,默认为红色

如果您正在使用类,兼容的解决方案:

<div
<p [ngClass]="{'text-red': true, 'text-white': false}"> 
some text...
</p>
</div>

与class在你的CSS文件

.text-red: { 
color:red;
}
.text-white: { 
color:white;
}

最新更新