与Angular2 two-way data binding类似,我有一个父组件和一个子组件。在父级中,我通过属性更改传递给子组件的值。孩子的财产名为percentage
。
https://gist.github.com/ideadapt/59c96d01bacbf3222096
我想将属性值绑定到html属性值。喜欢:< div style =" width:{{percentage}}%">。我没有找到任何有效的语法。所以我最终使用了一个更改侦听器来执行一些手动DOM更新:
this.progressElement = DOM.querySelector(element.nativeElement, '.progress');
DOM.setAttribute(this.progressElement, "style", `width: ${this.percentage}%`);
有更优雅的方法来实现这个目标吗?
答案 0 :(得分:59)
您可以对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;
}
答案 1 :(得分:38)
使用NgStyle
,其作用类似于Angular 1.自alpha-30以来,angular2/directives
中提供了NgStyle:
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>