Angular2绑定属性值

bub*_*lez 24 data-binding attributes angular

Angular2双向数据绑定类似,我有一个父组件和一个子组件.在父级中,我通过属性更改传递给子组件的值.孩子的财产被命名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}%`);
Run Code Online (Sandbox Code Playgroud)

是否有更优雅的方式来实现这一目标?

Den*_*din 60

您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)


Ang*_*ity 39

使用NgStyle,类似于Angular 1.由于alpha-30,NgStyle可用于angular2/directives:

import {NgStyle} from 'angular2/directives';
Run Code Online (Sandbox Code Playgroud)

然后包含NgStyle在指令列表中,这应该工作(这里有一些例子):

@View({
    directives: [NgStyle]
    template: `
        <div class="all">
            <div class="progress" [ng-style]="{'width': percentage + '%'}"></div>
            <span class="label">{{percentage}}</span>
        </div>
    `
})
Run Code Online (Sandbox Code Playgroud)

或者,不使用NgStyle,这也可以很好地工作:

<div class="progress" [style.width]="percentage + '%'"></div>
Run Code Online (Sandbox Code Playgroud)

  • 我们应该使用[style.width.px]或一些单位指标 (3认同)