Angular 2 中的 ngStyle 和 ngClass

ngStyle and ngClass in Angular 2

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

Angular 文档 https://angular.io/docs/js/latest/api/common/NgStyle-directive.html 中的 plnkr link 已过时,它使用 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'
  }
}

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

//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 文档:

The result of an expression evaluation is interpreted differently depending on type of the expression evaluation result:

string - all the CSS classes listed in a string (space delimited) are added
Array - all the CSS classes (Array elements) are added
Object - each key corresponds to a CSS class name while values are interpreted as expressions evaluating to Boolean. If a given expression evaluates to true a corresponding CSS class is added - otherwise it is removed.

@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