Using Multiple Structural Directives

Sometimes we'll want to combine multiple structural directives together, like iterating using ngFor but wanting to do an ngIf to make sure that the value matches some or multiple conditions. Combining structural directives can lead to unexpected results however, so Angular requires that a template can only be bound to one directive at a time. To apply multiple directives we'll have to expand the sugared syntax or nest template tags.

  1. @Component({
  2. selector: 'app-root',
  3. template: `
  4. <template ngFor [ngForOf]="[1,2,3,4,5,6]" let-item>
  5. <div *ngIf="item > 3">
  6. {{item}}
  7. </div>
  8. </template>
  9. `
  10. })

View Example

The previous tabs example can use ngFor and ngSwitch if the tab title and content is abstracted away into the component class.

  1. import {Component} from '@angular/core';
  2. @Component({
  3. selector: 'app-root',
  4. template: `
  5. <div class="tabs-selection">
  6. <tab
  7. *ngFor="let tab of tabs; let i = index"
  8. [active]="isSelected(i)"
  9. (click)="setTab(i)">
  10. {{ tab.title }}
  11. </tab>
  12. </div>
  13. <div [ngSwitch]="tabNumber">
  14. <template ngFor [ngForOf]="tabs" let-tab let-i="index">
  15. <tab-content *ngSwitchCase="i">
  16. {{tab.content}}
  17. </tab-content>
  18. </template>
  19. <tab-content *ngSwitchDefault>Select a tab</tab-content>
  20. </div>
  21. `
  22. })
  23. export class AppComponent {
  24. tabNumber: number = -1;
  25. tabs = [
  26. { title: 'Tab 1', content: 'Tab content 1' },
  27. { title: 'Tab 2', content: 'Tab content 2' },
  28. { title: 'Tab 3', content: 'Tab content 3' },
  29. ];
  30. setTab(num: number) {
  31. this.tabNumber = num;
  32. }
  33. isSelected(num: number) {
  34. return this.tabNumber === i;
  35. }
  36. }

View Example

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