Angular2 Bind Attribute Value

26,317

Solution 1

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>

Solution 2

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;
}
Share:
26,317

Related videos on Youtube

bubblez
Author by

bubblez

Updated on January 03, 2020

Comments

  • bubblez
    bubblez over 4 years

    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?

  • Kishore Relangi
    Kishore Relangi almost 8 years
    we should use [style.width.px] or some units indicator