MyInternships.in

Directives, Pipes & Templates

Angular ngFor Directive

*ngFor repeats an element once for each item in a collection, and exposes useful local variables — index, first, last, even and odd — for the current iteration.


What is ngFor Directive in Angular?

*ngFor repeats an element once for each item in a collection, and exposes useful local variables — index, first, last, even and odd — for the current iteration.

ngFor Directive example

ngFor with index and trackBy
HTML
<li *ngFor="let job of jobs; let i = index; trackBy: trackById"
    [class.first]="i === 0">
  {{ i + 1 }}. {{ job.title }}
</li>

The trackBy function

TypeScript
trackById(index: number, job: Job): string {
  return job.id;
}

Without trackBy, replacing the array — for example after a refetch — makes Angular destroy and recreate every DOM node. trackBy tells it to match items by id, so unchanged rows are left alone.

Key points to remember

  • Available locals: index, first, last, even, odd, count.
  • trackBy matters for performance and for preserving focus and animations in long lists.
  • The modern equivalent is @for, where track is mandatory rather than optional.

Common mistakes with ngFor Directive

  • Omitting trackBy on a list that refreshes, causing full re-renders and lost input focus.
  • Combining *ngFor with *ngIf on the same element.

Angular ngFor Directive— Interview Questions & FAQs

What does trackBy do in ngFor?+

It tells Angular how to identify each item across renders. With it, Angular updates only changed rows instead of destroying and rebuilding the whole list — which also preserves focus, scroll and animation state.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships