NgStyle Directive

Angular provides a built-in directive, ngStyle, to modify a component or element's style attribute. Here's an example:

  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

Notice that binding a directive works the exact same way as component attribute bindings. Here, we're binding an expression, an object literal, to the ngStyle directive so the directive name must be enclosed in square brackets. ngStyle accepts an object whose properties and values define that element's style. In this case, we can see that both kebab case and lower camel case can be used when specifying a style property. Also notice that both the html style attribute and Angular ngStyle directive are combined when styling the element.

We can remove the style properties out of the template into the component as a property object, which then gets assigned to NgStyle using property binding. This allows dynamic changes to the values as well as provides the flexibility to add and remove style properties.

  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. }

原文: https://angular-2-training-book.rangle.io/handout/directives/ng_style_directive.html