NgSwitch Directives

ngSwitch is actually comprised of two directives, an attribute directive and a structural directive. It's very similar to a switch statement in JavaScript and other programming languages, but in the template.

  1. @Component({
  2. selector: 'app-root',
  3. template: `
  4. <div class="tabs-selection">
  5. <app-tab [active]="isSelected(1)" (click)="setTab(1)">Tab 1</app-tab>
  6. <app-tab [active]="isSelected(2)" (click)="setTab(2)">Tab 2</app-tab>
  7. <app-tab [active]="isSelected(3)" (click)="setTab(3)">Tab 3</app-tab>
  8. </div>
  9. <div [ngSwitch]="tab">
  10. <app-tab-content *ngSwitchCase="1">Tab content 1</app-tab-content>
  11. <app-tab-content *ngSwitchCase="2">Tab content 2</app-tab-content>
  12. <app-tab-content *ngSwitchCase="3"><app-tab-3></app-tab-3></app-tab-content>
  13. <app-tab-content *ngSwitchDefault>Select a tab</app-tab-content>
  14. </div>
  15. `
  16. })
  17. export class AppComponent {
  18. tab: number = 0;
  19. setTab(num: number) {
  20. this.tab = num;
  21. }
  22. isSelected(num: number) {
  23. return this.tab === num;
  24. }
  25. }

View Example

Here we see the ngSwitch attribute directive being attached to an element. This expression bound to the directive defines what will compared against in the switch structural directives. If an expression bound to ngSwitchCase matches the one given to ngSwitch, those components are created and the others destroyed. If none of the cases match, then components that have ngSwitchDefault bound to them will be created and the others destroyed. Note that multiple components can be matched using ngSwitchCase and in those cases all matching components will be created. Since components are created or destroyed be aware of the costs in doing so.

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