gpt4 book ai didi

angular - Angular 2 中的 ngStyle 和 ngClass

转载 作者:太空狗 更新时间:2023-10-29 17:43:33 24 4
gpt4 key购买 nike

我不确定如何在最新的 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'
}
}

最佳答案

在这两种情况下,none 应该是带引号的 'none'。因为您应该将 string 值分配给属性 displaynone(不带引号)将在运行时进行评估并返回 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 文档:

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

关于angular - Angular 2 中的 ngStyle 和 ngClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com