NgFor Directive

The NgFor directive is a way of repeating a template by using each item of an iterable as that template's context.

  1. @Component({
  2. selector: 'app-root',
  3. template: `
  4. <app-for-example *ngFor="let episode of episodes" [episode]="episode">
  5. {{episode.title}}
  6. </app-for-example>
  7. `
  8. })
  9. export class AppComponent {
  10. episodes = [
  11. { title: 'Winter Is Coming', director: 'Tim Van Patten' },
  12. { title: 'The Kingsroad', director: 'Tim Van Patten' },
  13. { title: 'Lord Snow', director: 'Brian Kirk' },
  14. { title: 'Cripples, Bastards, and Broken Things', director: 'Brian Kirk' },
  15. { title: 'The Wolf and the Lion', director: 'Brian Kirk' },
  16. { title: 'A Golden Crown', director: 'Daniel Minahan' },
  17. { title: 'You Win or You Die', director: 'Daniel Minahan' },
  18. { title: 'The Pointy End', director: 'Daniel Minahan' }
  19. ];
  20. }

View Example

The NgFor directive has a different syntax from other directives we've seen. If you're familiar with the for…of statement, you'll notice that they're almost identical. NgFor lets you specify an iterable object to iterate over and the name to refer to each item by inside the scope. In our example, you can see that episode is available for interpolation as well as property binding. The directive does some extra parsing so that when this is expanded to template form, it looks a bit different:

  1. @Component({
  2. selector: 'app',
  3. template: `
  4. <template ngFor [ngForOf]="episodes" let-episode>
  5. <app-for-example [episode]="episode">
  6. {{episode.title}}
  7. </app-for-example>
  8. </template>
  9. `
  10. })

View Example

Notice that there is an odd let-episode property on the template element. The NgFor directive provides some variables as context within its scope. let-episode is a context binding and here it takes on the value of each item of the iterable.

Local Variables

NgFor also provides other values that can be aliased to local variables:

  • index - position of the current item in the iterable starting at 0
  • first - true if the current item is the first item in the iterable
  • last - true if the current item is the last item in the iterable
  • even - true if the current index is an even number
  • odd - true if the current index is an odd number

    1. @Component({
    2. selector: 'app-root',
    3. template: `
    4. <app-for-example
    5. *ngFor="let episode of episodes; let i = index; let isOdd = odd"
    6. [episode]="episode"
    7. [ngClass]="{ odd: isOdd }">
    8. {{i+1}}. {{episode.title}}
    9. </app-for-example>
    10. <hr>
    11. <h2>Desugared</h2>
    12. <template ngFor [ngForOf]="episodes" let-episode let-i="index" let-isOdd="odd">
    13. <for-example [episode]="episode" [ngClass]="{ odd: isOdd }">
    14. {{i+1}}. {{episode.title}}
    15. </for-example>
    16. </template>
    17. `
    18. })

View Example

trackBy

Often NgFor is used to iterate through a list of objects with a unique ID field. In this case, we can provide a trackBy function which helps Angular keep track of items in the list so that it can detect which items have been added or removed and improve performance.

Angular will try and track objects by reference to determine which items should be created and destroyed. However, if you replace the list with a new source of objects, perhaps as a result of an API request - we can get some extra performance by telling Angular how we want to keep track of things.

For example, if the Add Episode button was to make a request and return a new list of episodes, we might not want to destroy and re-create every item in the list. If the episodes have a unique ID, we could add a trackBy function:

  1. @Component({
  2. selector: 'app-root',
  3. template: `
  4. <button
  5. (click)="addOtherEpisode()"
  6. [disabled]="otherEpisodes.length === 0">
  7. Add Episode
  8. </button>
  9. <app-for-example
  10. *ngFor="let episode of episodes;
  11. let i = index; let isOdd = odd;
  12. trackBy: trackById" [episode]="episode"
  13. [ngClass]="{ odd: isOdd }">
  14. {{episode.title}}
  15. </app-for-example>
  16. `
  17. })
  18. export class AppComponent {
  19. otherEpisodes = [
  20. { title: 'Two Swords', director: 'D. B. Weiss', id: 8 },
  21. { title: 'The Lion and the Rose', director: 'Alex Graves', id: 9 },
  22. { title: 'Breaker of Chains', director: 'Michelle MacLaren', id: 10 },
  23. { title: 'Oathkeeper', director: 'Michelle MacLaren', id: 11 }]
  24. episodes = [
  25. { title: 'Winter Is Coming', director: 'Tim Van Patten', id: 0 },
  26. { title: 'The Kingsroad', director: 'Tim Van Patten', id: 1 },
  27. { title: 'Lord Snow', director: 'Brian Kirk', id: 2 },
  28. { title: 'Cripples, Bastards, and Broken Things', director: 'Brian Kirk', id: 3 },
  29. { title: 'The Wolf and the Lion', director: 'Brian Kirk', id: 4 },
  30. { title: 'A Golden Crown', director: 'Daniel Minahan', id: 5 },
  31. { title: 'You Win or You Die', director: 'Daniel Minahan', id: 6 }
  32. { title: 'The Pointy End', director: 'Daniel Minahan', id: 7 }
  33. ];
  34. addOtherEpisode() {
  35. // We want to create a new object reference for sake of example
  36. let episodesCopy = JSON.parse(JSON.stringify(this.episodes))
  37. this.episodes=[...episodesCopy,this.otherEpisodes.pop()];
  38. }
  39. trackById(index: number, episode: any): number {
  40. return episode.id;
  41. }
  42. }

To see how this can affect the ForExample component, let's add some logging to it.

  1. export class ForExampleComponent {
  2. @Input() episode;
  3. ngOnInit() {
  4. console.log('component created', this.episode)
  5. }
  6. ngOnDestroy() {
  7. console.log('destroying component', this.episode)
  8. }
  9. }

View Example

When we view the example, as we click on Add Episode, we can see console output indicating that only one component was created - for the newly added item to the list.

However, if we were to remove the trackBy from the *ngFor - every time we click the button, we would see the items in the component getting destroyed and recreated.

View Example Without trackBy

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