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?

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

40

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>

1 Comment

we should use [style.width.px] or some units indicator

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.