在这两种情况下,none 应该是带有引号的'none'。因为您应该将string 值分配给属性display。 none(不带 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