Skip to the page

Components and templates · core

Built-in control flow, track and pipes

The built-in @if, @for and @switch blocks replaced *ngIf and *ngFor in new code. @for needs track, and a pure pipe is the right place for template formatting.

The notes

What you must know

  • @if, @else, @for and @switch are template blocks, not directives. New code uses them instead of *ngIf and *ngFor (facts.md).
  • @for requires a track expression. It tells Angular how to recognise an item between renders.
  • track order uses object identity. If every refresh returns new objects, every row is destroyed and created again: lost focus, lost input state, slow work. Dev mode warns with NG0956.
  • Fix: track order.id, a stable unique key. Duplicate keys give wrong results.
  • A method call in a template runs on every check. A pure pipe runs again only when its input changes by reference.
  • A pipe is a class with @Pipe({ name }) and transform. It is standalone and goes into the component imports.
  • *ngIf and *ngFor still work in old code. Say which is old.

The red pen

Common traps: mistake → fix

  • Mistake: track $index is always safe

    Fix: it is fine for a list that never reorders, but it reuses the wrong DOM when items move or are inserted.

  • Mistake: A pure pipe runs on every check

    Fix: it runs only when its input reference changes.

  • Mistake: @for is the same as *ngFor with new syntax

    Fix: track is required and the block is faster and built in.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you show a list in a modern Angular template?
  2. Why does @for need track?
  3. A list loses input focus every time it refreshes. Why?
  4. When would you write a pipe instead of calling a method in the template?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview