ng-class 和 ng-style 有什么区别?

问题描述 投票:0回答:5

ng-class
ng-style
似乎都是动态设置CSS类的方法。他们有什么区别?

css angularjs angularjs-directive
5个回答
38
投票

ng-style 用于将 javascript 对象插入到 style 属性中,而不是 css 类中。

以下指令将被翻译为 style="color:red"

ng-style="{color: 'red'}"

并且 ng-class 指令将您的对象转换为 class 属性。

isDeleted 变量为 true 时,以下内容将被翻译为 class="deleted"

ng-class="{'deleted': isDeleted}"

注:

ng-style 还有一个用例。如果你想在 style 属性中插入一些东西,你应该考虑使用 ng-style。否则,如文档所示,在 Internet Explorer 11 之前,这将不起作用。

所以,不要使用样式:

style="width: {{progress}}"

使用ng风格:

ng-style="{'width':progress}"

6
投票

ng-class
中,您正在加载在某个地方定义的CSS类,例如Bootstrap。在
ng-style
中,您可以设置您希望该元素具有的 CSS 样式,例如:

ng-style="{ 'background-color': person.email == selectedPerson.email ? 'lightgray' : ' '}" //background-color is a style

has-error
是在某处定义的类,由样式组成:

ng-class="{ 'has-error’: !theForm.email.$valid, 'has-success':theForm.email.$valid}

1
投票

来自官方文档:https://angular.io/api/common/NgClass

  1. 这些是使用 ngClass 的不同方式

    ...

    <some-element [ngClass]="['first', 'second']">...</some-element>
    
    <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some- 
    

    元素>

    <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
    
    <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
    

2。与 ngStyle 类似,您可以执行以下操作:

**< some-element [ngStyle]="{'font-style': styleExp}">...</some-element>**
  • 您的 styleExp 可以是任何计算结果为您正在设置的属性的合法值的值,例如上例中的字体大小

  • 或者,

    ****< some-element [ngStyle]="objExp">...****

  • 其中 objExp 是一个包含样式属性键值对的对象 例如{ 宽度:40,边距:'2em' } 等等


0
投票

理论上它们都是不同的,但实际上在某些时候它们都变得相同

ngStyle 用于在运行时动态添加样式并且

ngClass用于在运行时动态添加一些类,但类还保存一些CSS内容,因此间接地你也在此处动态添加CSS


0
投票

ng类

ngClass 属性指令有助于有条件地添加和删除 CSS 类名。

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h1 [ngClass]="[isActive ? 'my-color' : 'red-color']">Hello angular</h1>
    <button (click)="changeColor()">Change color</button>
  `,
  styles: [
    `
      .my-color {
        background-color: aqua;
      }

      .red-color {
        background-color: red;
      }
    `,
  ],
})
export class AppComponent {
  isActive = false;

  changeColor() {
    this.isActive = !this.isActive;
  }
}

ng风格

ngStyle 属性指令帮助我们动态添加和删除内联样式。

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h1 [ngStyle]="{ backgroundColor: h1color }">Hello angular</h1>
    <button (click)="changeColor()">Change color</button>
  `,
})
export class AppComponent {
  h1color = 'red';

  changeColor() {
    this.h1color = 'green';
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.