【问题标题】:ngStyle and ngClass in Angular 2Angular 2 中的 ngStyle 和 ngClass
【发布时间】:2016-07-14 13:37:38
【问题描述】:

我不确定如何在最新的 beta-12 中使用 ngStyle 指令。有人可以澄清一下吗?

Angular 文档https://angular.io/docs/js/latest/api/common/NgStyle-directive.html 中的 plnkr 链接已过时,它使用 alpha 版本。

我尝试了这些语法,但似乎不起作用。我

 [ngStyle]="{'display': none}"
 [style.display]="none"

http://plnkr.co/edit/U9EJuIhFqxY9t2sULMdw

import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2 [ngStyle]="{'display': none}">Hello {{name}}</h2>
      <h2 [style.display]="none">Hello {{name}}</h2>
    </div>
  `,
  directives: []
})
export class App {
  constructor() {
    this.name = 'Angular2'
  }
}

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    在这两种情况下,none 应该是带有引号的'none'。因为您应该将string 值分配给属性displaynone(不带 qoutes)将在运行时评估并返回 undefined,这不是 css 属性 display 的可接受值

    //our root app component
    import {Component} from 'angular2/core'
    @Component({
      selector: 'my-app',
      providers: [],
      template: `
        <div>
          <h2 [ngStyle]="{'display': 'none'}">Hello {{name}}</h2>
          <h2 [style.display]="'none'">Hello {{name}}</h2>
        </div>
      `,
      directives: []
    })
    export class App {
      constructor() {
        this.name = 'Angular2'
      }
    }
    

    Here is your plunker fixed

    更新

    这是来自 NgClass directive 的 angular2 文档:

    表达式求值的结果有不同的解释 取决于表达式评估结果的类型:

    string - 字符串中列出的所有 CSS 类(以空格分隔) 已添加
    Array - 添加所有 CSS 类(数组元素)
    Object - 每个键对应一个 CSS 类名,而值被解释 作为评估为布尔值的表达式。如果给定的表达式计算 为 true 添加相应的 CSS 类 - 否则将其删除。

    @Component({
      selector: 'my-app',
      providers: [],
      styles:['.hide{display:none}',
      '.border{border:3px solid blue}',
      '.redBack{background-color:red}'
      ],
      template: `
        <div>
          <h2 [ngStyle]="{'display': 'none'}">Hello {{name}}</h2>
          <h2 [style.display]="'none'">Hello {{name}}</h2>
          <h2 [ngClass]="'redBack'">Hello {{name}}</h2>  // just normal string
          <h2 [ngClass]="{'hide':hideFlag}">Hello {{name}}</h2>  // will add class 'hide' if hideFlag is true
          <h2 [ngClass]="mulClasses">Hello {{name}}</h2>  // will add an array of classes ['border','redBack']
        </div>
      `,
      directives: []
    })
    export class App {
      hideFlag = false;
      mulClasses = ['border','redBack']
    
      constructor() {
        this.name = 'Angular2'
      }
    }
    

    here is the example in plunker

    【讨论】:

    • @Sudhakar,不客气,我已经更新了我的答案以供参考
    • 赞成对文档的引用,一个 plnkr 和一个很好的解释!
    • @EricMartinez 非常感谢
    猜你喜欢
    • 2018-08-28
    • 2022-12-14
    • 2018-05-02
    • 2021-11-14
    • 2018-10-18
    • 2018-02-12
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多