当前位置:   article > 正文

Angular 2 中的样式绑定和 NgStyle

Angular 2 中的样式绑定和 NgStyle

在 Angular 2 模板中绑定内联样式很容易。以下是一个绑定单个样式值的示例:

你还可以指定单位,例如在这里我们将单位设置为 em,但也可以使用 px、% 或 rem:

<p [style.font-size.em]="'3'">
  A paragraph at 3em!
</p>
  • 1
  • 2
  • 3

以下是根据组件属性有条件地设置样式值的方法:

<p [style.font-size.px]="isImportant ? '30' : '16'">
  Some text that may be important.
</p>
  • 1
  • 2
  • 3

NgStyle 用于多个值

简单的样式绑定适用于单个值,但要应用多个样式,最简单的方法是使用 NgStyle:

<p [ngStyle]="myStyles">
  You say tomato, I say tomato
</p>
  • 1
  • 2
  • 3

然后 myStyles 将是组件中包含以 CSS 属性名称为键的对象的属性,如下所示:

myStyles = {
'background-color': 'lime',
'font-size': '20px',
'font-weight': 'bold'
}
  • 1
  • 2
  • 3
  • 4
  • 5

或者可以像这样内联提供对象:

<p [ngStyle]="{'background-color': 'lime',
    'font-size': '20px',
    'font-weight': 'bold'}">
  You say tomato, I say tomato
</p>
  • 1
  • 2
  • 3
  • 4
  • 5

或者对象可以是方法的返回值:

<p [ngStyle]="setMyStyles()">
  You say tomato, I say tomato
</p>
  • 1
  • 2
  • 3

在相关的组件类中

setMyStyles() {
  let styles = {
    'background-color': this.user.isExpired ? 'red' : 'transparent',
    'font-weight': this.isImportant ? 'bold' : 'normal'
  };
  return styles;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

另请参阅

  • Class binding + NgClass
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
  

闽ICP备14008679号