【问题标题】:Change color dynamically using ngClass or ngStyle in Angular在 Angular 中使用 ngClass 或 ngStyle 动态更改颜色
【发布时间】:2021-11-14 07:51:41
【问题描述】:

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

提前致谢。

Css 文件

.text-color: {
 color:red;
}

html

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

【问题讨论】:

  • 两者都行。 ngClass 更改一个类(您可以对其应用 CSS),ngStyle 直接内联更改 CSS。

标签: javascript html css angular typescript


【解决方案1】:

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

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

在你的 css 文件中添加类

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

【讨论】:

    【解决方案2】:

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

    说明: p 标签的按钮颜色的 onclick 将变为绿色,默认为红色

    【讨论】:

      【解决方案3】:

      您可以只绑定到 HTML 属性:

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

      在您的组件中,创建类属性来跟踪点击状态:

      divClicked = false
      

      Stackblitz

      【讨论】:

        猜你喜欢
        • 2018-10-08
        • 2016-07-14
        • 2019-05-28
        • 2021-06-04
        • 2020-05-11
        • 2019-09-28
        • 1970-01-01
        • 2021-02-23
        • 2018-08-28
        相关资源
        最近更新 更多