NgStyle 指令

Angular 2提供了一个内置的指令ngStyle来修改组件或元素的style属性。这里有一个例子:

  1. @Component({
  2. selector: 'app-style-example',
  3. template: `
  4. <p style="padding: 1rem"
  5. [ngStyle]="{
  6. 'color': 'red',
  7. 'font-weight': 'bold',
  8. 'borderBottom': borderStyle
  9. }">
  10. <ng-content></ng-content>
  11. </p>
  12. `
  13. })
  14. export class StyleExampleComponent {
  15. borderStyle = '1px solid black';
  16. }

View Example

请注意,绑定指令的方式与组件属性绑定完全相同。 这里,我们将一个表达式和一个对象字面量绑定到ngStyle指令,因此指令名称必须用方括号括起来。 ngStyle接受一个对象,其属性和值定义该元素的样式。 在这种情况下,我们可以看到,当指定style属性时,可以使用短横线式(kebab case)和小驼峰式(lower camel case)命名。 还要注意,在对元素进行样式设计时,html的style 属性和Angular ngStyle指令都是合并的。

我们可以将样式属性从模板中移除到组件中作为属性对象,然后使用属性绑定将其分配给NgStyle。 这允许对值的动态更改,而且让添加和删除样式属性更加灵活。

  1. @Component({
  2. selector: 'app-style-example',
  3. template: `
  4. <p style="padding: 1rem"
  5. [ngStyle]="alertStyles">
  6. <ng-content></ng-content>
  7. </p>
  8. `
  9. })
  10. export class StyleExampleComponent {
  11. borderStyle = '1px solid black';
  12. alertStyles = {
  13. 'color': 'red',
  14. 'font-weight': 'bold',
  15. 'borderBottom': this.borderStyle
  16. };
  17. }