26

Similar to Angular2 two-way data binding, I have a parent and a child component. In the parent I change the value that is passed to the child component via property. The property of the child is named percentage.

https://gist.github.com/ideadapt/59c96d01bacbf3222096

I want to bind the property value to a html attribute value. Like: <div style="width: {{percentage}}%">. I didn't find any syntax that worked. So I ended up using a change listener that does some manual DOM update:

this.progressElement = DOM.querySelector(element.nativeElement, '.progress');
DOM.setAttribute(this.progressElement, "style", `width: ${this.percentage}%`);

Is there a more elegant way to accomplish this?

Community
  • 1
  • 1
bubblez
  • 814
  • 1
  • 8
  • 14

2 Answers2

64

You can use percentage binding for CSS properties: [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;
}
DenisKolodin
  • 13,501
  • 3
  • 62
  • 65
41

Use NgStyle, which works similar to Angular 1. Since alpha-30, NgStyle is available in angular2/directives:

import {NgStyle} from 'angular2/directives';

Then include NgStyle in the directives list, this should work (here are some examples):

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

Alternatively and without using NgStyle, this would work well too:

<div class="progress" [style.width]="percentage + '%'"></div>
Angular University
  • 42,341
  • 15
  • 74
  • 81