它很容易绑定内联样式在您的角度2模板。下面是如何绑定单个样式值的方法,例如:
1<p [style.background-color]="'darkorchid'">
2 Quite something!
3</p>
您也可以指定单位,例如,我们在em中设置单位,但也可以使用px、%或rem:
1<p [style.font-size.em]="'3'">
2 A paragraph at 3em!
3</p>
下面介绍如何根据组件的属性有条件地设置样式值:
1<p [style.font-size.px]="isImportant ? '30' : '16'">
2 Some text that may be important.
3</p>
NgStyle支持多个值
简单的样式绑定对于单值非常有用,但对于应用多个样式,最简单的方法是使用NgStyle:
1<p [ngStyle]="myStyles">
2 You say tomato, I say tomato
3</p>
然后,myStyles将是组件中的一个属性,该组件包含一个以css属性名称为键的对象,如下所示:
1myStyles = {
2'background-color': 'lime',
3'font-size': '20px',
4'font-weight': 'bold'
5}
或者可以像这样内联提供:
1<p [ngStyle]="{'background-color': 'lime',
2 'font-size': '20px',
3 'font-weight': 'bold'}">
4 You say tomato, I say tomato
5</p>
或者,该对象可以是方法的返回值:
1<p [ngStyle]="setMyStyles()">
2 You say tomato, I say tomato
3</p>
在关联的组件类中
1setMyStyles() {
2 let styles = {
3 'background-color': this.user.isExpired ? 'red' : 'transparent',
4 'font-weight': this.isImportant ? 'bold' : 'normal'
5 };
6 return styles;
7}