繁体   English   中英

Angular 2中的ngStyle和ngClass

[英]ngStyle and ngClass in Angular 2

我不确定如何将ngStyle指令与最新的beta-12一起使用。 请有人澄清一下。

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'
  }
}

在这两种情况下, 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'
  }
}

这是你的plunker固定

更新

这是来自NgClass指令的 angular2 docs:

表达式评估的结果根据表达式评估结果的类型进行不同的解释:

string - 添加字符串中列出的所有CSS类(以空格分隔)
数组 - 添加了所有CSS类(数组元素)
Object - 每个键对应一个CSS类名,而值被解释为求值为Boolean的表达式。 如果给定的表达式求值为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中的例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM