2015-07-09 69 views
21

Angular2 two-way data binding类似,我有一个父组件和一个子组件。在父级中,我通过属性更改传递给子组件的值。儿童的财产被命名为percentageAngular2绑定属性值

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}%`); 

有没有做到这一点更优雅的方式?

回答

33

使用NgStyle,其工作原理类似于角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> 
+3

我们应该用[style.width.px]或某些单位指标 –

51

您可以使用百分比结合的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; 
}