加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2中的ngStyle和ngClass

发布时间:2020-12-17 17:56:26 所属栏目:安全 来源:网络整理
导读:我不确定如何将ngStyle指令与最新的beta-12一起使用.请有人澄清一下. Angular docs https://angular.io/docs/js/latest/api/common/NgStyle-directive.html中的plnkr链接已过时,它使用alpha版本. 我尝试了这些语法,但似乎没有用.一世 [ngStyle]="{'display':
我不确定如何将ngStyle指令与最新的beta-12一起使用.请有人澄清一下.

Angular docs 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(不带qoutes)将在运行时进行计算并返回undefined,这不是css属性显示的可接受值

//our root app component
import {Component} from 'angular2/core'
@Component({
  selector: 'my-app',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 docs:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读