赞
踩
在 Angular 2 模板中绑定内联样式很容易。以下是一个绑定单个样式值的示例:
你还可以指定单位,例如在这里我们将单位设置为 em,但也可以使用 px、% 或 rem:
<p [style.font-size.em]="'3'">
A paragraph at 3em!
</p>
以下是根据组件属性有条件地设置样式值的方法:
<p [style.font-size.px]="isImportant ? '30' : '16'">
Some text that may be important.
</p>
简单的样式绑定适用于单个值,但要应用多个样式,最简单的方法是使用 NgStyle:
<p [ngStyle]="myStyles">
You say tomato, I say tomato
</p>
然后 myStyles 将是组件中包含以 CSS 属性名称为键的对象的属性,如下所示:
myStyles = {
'background-color': 'lime',
'font-size': '20px',
'font-weight': 'bold'
}
或者可以像这样内联提供对象:
<p [ngStyle]="{'background-color': 'lime',
'font-size': '20px',
'font-weight': 'bold'}">
You say tomato, I say tomato
</p>
或者对象可以是方法的返回值:
<p [ngStyle]="setMyStyles()">
You say tomato, I say tomato
</p>
在相关的组件类中
setMyStyles() {
let styles = {
'background-color': this.user.isExpired ? 'red' : 'transparent',
'font-weight': this.isImportant ? 'bold' : 'normal'
};
return styles;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。