Angular2 绑定属性值
Angular2 Bind Attribute Value
类似于,我有一个parent和一个child组件。在 parent 中,我更改了通过 属性 传递给 child 组件的值。 child 的 属性 被命名为 percentage
.
https://gist.github.com/ideadapt/59c96d01bacbf3222096
我想将 属性 值绑定到 html 属性值。喜欢:
。我没有找到任何有效的语法。所以我最终使用了一个更改侦听器来执行一些手动 DOM 更新:
this.progressElement = DOM.querySelector(element.nativeElement, '.progress');
DOM.setAttribute(this.progressElement, "style", `width: ${this.percentage}%`);
有没有更优雅的方法来完成这个?
使用NgStyle
,其工作方式类似于Angular 1.自alpha-30以来,NgStyle在angular2/directives
:
中可用
import {NgStyle} from 'angular2/directives';
然后在指令列表中包含 NgStyle
,这应该有效(here 是一些示例):
@View({
directives: [NgStyle]
template: `
<div class="all">
<div class="progress" [ng-style]="{'width': percentage + '%'}"></div>
<span class="label">{{percentage}}</span>
</div>
`
})
或者不使用 NgStyle
,这也很有效:
<div class="progress" [style.width]="percentage + '%'"></div>
您可以对 CSS 属性使用 百分比绑定:[style.width.%]
import {Component, Input} from 'angular2/core';
@Component({
selector: 'progress-bar',
template: `
<div class="progress-bar">
<div [style.width.%]="value"> {{ value }}% </div>
</div>
`,
})
export class ProgressBar {
@Input() private value: number;
}
类似于percentage
.
https://gist.github.com/ideadapt/59c96d01bacbf3222096
我想将 属性 值绑定到 html 属性值。喜欢:
。我没有找到任何有效的语法。所以我最终使用了一个更改侦听器来执行一些手动 DOM 更新:
this.progressElement = DOM.querySelector(element.nativeElement, '.progress');
DOM.setAttribute(this.progressElement, "style", `width: ${this.percentage}%`);
有没有更优雅的方法来完成这个?
使用NgStyle
,其工作方式类似于Angular 1.自alpha-30以来,NgStyle在angular2/directives
:
import {NgStyle} from 'angular2/directives';
然后在指令列表中包含 NgStyle
,这应该有效(here 是一些示例):
@View({
directives: [NgStyle]
template: `
<div class="all">
<div class="progress" [ng-style]="{'width': percentage + '%'}"></div>
<span class="label">{{percentage}}</span>
</div>
`
})
或者不使用 NgStyle
,这也很有效:
<div class="progress" [style.width]="percentage + '%'"></div>
您可以对 CSS 属性使用 百分比绑定:[style.width.%]
import {Component, Input} from 'angular2/core';
@Component({
selector: 'progress-bar',
template: `
<div class="progress-bar">
<div [style.width.%]="value"> {{ value }}% </div>
</div>
`,
})
export class ProgressBar {
@Input() private value: number;
}