Angular 2中的ngStyle和ngClass

4
我不确定如何在最新的beta-12版本中使用ngStyle指令。请问有人可以澄清一下吗?
Angular文档中的plnkr链接https://angular.io/docs/js/latest/api/common/NgStyle-directive.html已经过时,它使用了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'
  }
}
1个回答

11
在这两种情况下,none 应该带有引号,变成 'none'。因为你应该给属性 display 赋一个字符串值。none(没有引号)会在运行时被评估,并返回 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'
  }
}

这是已经修复的 plunker

更新

这段内容来自angular2文档中的NgClass指令:

表达式计算的结果根据其类型不同而解释如下:

字符串 - 填写在字符串中的所有CSS类(以空格分隔)都会被添加
数组 - 所有CSS类(数组元素)都会被添加
对象 - 每个键对应一个 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'
  }
}

这里是在 plunker 中的示例


@Sudhakar,欢迎您,我已经更新了我的答案供参考。 - Abdulrahman Alsoghayer
点赞给予文档、plnkr和良好解释的参考! - Eric Martinez
@EricMartinez 非常感谢。 - Abdulrahman Alsoghayer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接