NgClass Directive

The ngClass directive changes the class attribute that is bound to the component or element it's attached to. There are a few different ways of using the directive.

Binding a string

We can bind a string directly to the attribute. This works just like adding an html class attribute.

  1. @Component({
  2. selector: 'app-class-as-string',
  3. template: `
  4. <p ngClass="centered-text underlined" class="orange">
  5. <ng-content></ng-content>
  6. </p>
  7. `,
  8. styles: [`
  9. .centered-text {
  10. text-align: center;
  11. }
  12. .underlined {
  13. border-bottom: 1px solid #ccc;
  14. }
  15. .orange {
  16. color: orange;
  17. }
  18. `]
  19. })
  20. export class ClassAsStringComponent {
  21. }

View Example

In this case, we're binding a string directly so we avoid wrapping the directive in square brackets. Also notice that the ngClass works with the class attribute to combine the final classes.

Binding an array

  1. @Component({
  2. selector: 'app-class-as-array',
  3. template: `
  4. <p [ngClass]="['warning', 'big']">
  5. <ng-content></ng-content>
  6. </p>
  7. `,
  8. styles: [`
  9. .warning {
  10. color: red;
  11. font-weight: bold;
  12. }
  13. .big {
  14. font-size: 1.2rem;
  15. }
  16. `]
  17. })
  18. export class ClassAsArrayComponent {
  19. }

View Example

Here, since we are binding to the ngClass directive by using an expression, we need to wrap the directive name in square brackets. Passing in an array is useful when you want to have a function put together the list of applicable class names.

Binding an object

Lastly, an object can be bound to the directive. Angular applies each property name of that object to the component if that property is true.

  1. @Component({
  2. selector: 'app-class-as-object',
  3. template: `
  4. <p [ngClass]="{ card: true, dark: false, flat: flat }">
  5. <ng-content></ng-content>
  6. <br>
  7. <button type="button" (click)="flat=!flat">Toggle Flat</button>
  8. </p>
  9. `,
  10. styles: [`
  11. .card {
  12. border: 1px solid #eee;
  13. padding: 1rem;
  14. margin: 0.4rem;
  15. font-family: sans-serif;
  16. box-shadow: 2px 2px 2px #888888;
  17. }
  18. .dark {
  19. background-color: #444;
  20. border-color: #000;
  21. color: #fff;
  22. }
  23. .flat {
  24. box-shadow: none;
  25. }
  26. `]
  27. })
  28. export class ClassAsObjectComponent {
  29. flat: boolean = true;
  30. }

View Example

Here we can see that since the object's card and flat properties are true, those classes are applied but since dark is false, it's not applied.

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