Angular2 Bind Attribute Value
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;
}
Related videos on Youtube
bubblez
Updated on January 03, 2020Comments
-
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 almost 8 yearswe should use [style.width.px] or some units indicator