Angular2绑定属性值 [英] Angular2 Bind Attribute Value
问题描述
类似于 Angular2双向数据绑定,我有一个父级和一个子组件.在父级中,我更改通过属性传递给子级组件的值.子代的属性命名为percentage
.
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
我想将属性值绑定到html属性值.像:< div style ="width:{{percentage}}%">.我没有找到任何有效的语法.因此,我最终使用了一个进行一些手动DOM更新的更改侦听器:
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?
推荐答案
使用NgStyle
,其工作方式类似于Angular 1./CHANGELOG.md#200-alpha30-2015-07-07"rel =" noreferrer> alpha-30 ,NgStyle在angular2/directives
中可用:
Use NgStyle
, which works similar to Angular 1. Since alpha-30, NgStyle is available in angular2/directives
:
import {NgStyle} from 'angular2/directives';
然后在指令列表中包含NgStyle
,这应该可以正常工作(此处是一些示例):
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>
`
})
或者不用NgStyle
,这也可以很好地工作:
Alternatively and without using NgStyle
, this would work well too:
<div class="progress" [style.width]="percentage + '%'"></div>
这篇关于Angular2绑定属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!