Angular · Lesson 1

Components & templates

Standalone components, template bindings, signal inputs and outputs (`input()`, `output()`, `model()`), the built-in control flow (`@if`, `@for`, `@switch`, `@defer`), content projection and the component lifecycle.

13 min read

In short

  • Standalone components list what the template uses in imports
  • input(), output() and model() are the component's API
  • Data flows down with [ ], events flow up with ( )
  • @if, @for with track item.id, @switch, @defer
  • Never mutate inputs or arrays; replace them

On an Angular team, most of your day is spent writing components: a TypeScript class that holds state, plus a template that binds to it. This lesson covers how modern Angular writes them (standalone components, signal inputs, the built-in @if/@for control flow) and how the template actually behaves, because most template bugs come from not knowing what Angular does with a binding.

You'll also meet older code at work: NgModules, @Input(), *ngIf. Each section shows how to recognise it.

Angular itself can't run in the lab, so blocks that import @angular/* have no ▶ Try button. Plain TypeScript blocks do. The exercises rebuild the mechanisms (input transforms, pure pipes, input()/model(), content projection, the lifecycle order, @for tracking and a small control-flow renderer) in plain TypeScript.

A standalone component

import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { CurrencyPipe } from '@angular/common';

export interface CartItem {
  id: string;
  name: string;
  price: number;
  quantity: number;
}

@Component({
  selector: 'app-cart-line',
  imports: [CurrencyPipe],   // everything the template uses: components, directives, pipes
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <span class="name">{{ item().name }}</span>
    <span class="total">{{ lineTotal() | currency: 'EUR' }}</span>
    <button type="button" (click)="removed.emit(item().id)">Remove</button>
  `,
  styles: `
    :host { display: flex; gap: 1rem; }
    .total { font-weight: 600; }
  `,
})
export class CartLine {
  readonly item = input.required<CartItem>();
  readonly removed = output<string>();
  readonly lineTotal = computed(() => this.item().price * this.item().quantity);
}
  • Standalone is the default (since Angular 19, so there's no standalone: true any more). A component lists what its template uses in imports. Forget one and the compiler says 'app-x' is not a known element (NG8001).
  • selector is how other templates use it: <app-cart-line [item]="line" (removed)="remove($event)" />. Self-closing tags work for components.
  • template/templateUrl and styles/styleUrl. Styles are scoped to the component by default, and :host styles the component's own element.
  • The app starts with bootstrapApplication(App, appConfig), where appConfig.providers holds app-wide setup (provideRouter(routes), provideHttpClient()). There's no root module.
  • New projects (Angular 20 style guide) name files cart-line.ts, cart-line.html and the class CartLine. Older code uses cart-line.component.ts and CartLineComponent. Both are fine; follow your codebase.

Older code: components declared in an @NgModule({ declarations: [...] }), and templates get their dependencies from the module's imports. It works the same at runtime. New code shouldn't add modules.

Templates and bindings

SyntaxWhat it doesExample
{{ expr }}text interpolation{{ user().name }}
[prop]="expr"sets a DOM property or a component input[disabled]="saving()", [item]="line"
[attr.name]sets an HTML attribute[attr.aria-label]="label()", [attr.colspan]="span"
[class.x], [class]toggles one class / sets several[class.active]="selected()"
[style.x]sets one style, with an optional unit[style.width.px]="width()"
(event)="statement"listens to a DOM event or a component output(click)="save()", (keyup.enter)="search()"
[(x)]="value"two-way binding ([x] plus (xChange))[(quantity)]="qty"
#reftemplate reference to an element or component<input #q (keyup.enter)="search(q.value)">
@leta local template variable@let total = cart.total();
value | pipe: argformats a value with a pipe{{ price() | currency: 'EUR' }}

How Angular treats a binding:

  • On every check of the component, Angular re-evaluates each binding expression and compares the result with the previous one using Object.is. It only touches the DOM when the result changed. So expressions must be cheap and free of side effects. A method call like {{ total() }} that loops over an array runs on every check; a computed signal runs only when its inputs change.
  • Properties vs attributes. [value]="name" sets the value property, which is what the input shows. HTML attributes only set the initial state. Use [attr.x] for things that only exist as attributes (ARIA, colspan, data-*).
  • Static attributes are strings. <app-button disabled> passes the string '', and size="3" passes '3'. That's why inputs often use the booleanAttribute and numberAttribute transforms (exercise 1).
  • Interpolation turns null and undefined into an empty string and everything else into String(value):
▶ Try
// What {{ value }} renders, the same rule Angular uses
const interpolate = (value: unknown) => (typeof value === 'string' ? value : value == null ? '' : String(value));

for (const value of ['Ann', 42, 0, null, undefined, false, [1, 2], { id: 1 }]) {
  console.log(JSON.stringify(value) ?? 'undefined', '->', JSON.stringify(interpolate(value)));
}
  • Pipes are pure by default: Angular calls transform again only when an argument changes by reference. Push an item into an array and a pure filter pipe keeps showing the old result. Exercise 2 builds this.
  • Event bindings run a statement. $event is the DOM event, or the value an output emitted. With zone.js or zoneless, a template event also marks the component for checking, which is why a click handler that changes state updates the view.

Inputs, outputs and model()

import { Component, booleanAttribute, computed, input, model, numberAttribute, output } from '@angular/core';

export interface Product {
  id: string;
  name: string;
  price: number;
}

@Component({
  selector: 'app-product-card',
  template: `
    <h3>{{ product().name }}</h3>
    <button type="button" (click)="quantity.update((q) => q - 1)" [disabled]="disabled() || quantity() <= 1">-</button>
    <span>{{ quantity() }}</span>
    <button type="button" (click)="quantity.update((q) => q + 1)" [disabled]="disabled() || quantity() >= max()">+</button>
    <button type="button" (click)="addToCart.emit({ productId: product().id, quantity: quantity() })">Add</button>
  `,
})
export class ProductCard {
  readonly product = input.required<Product>();                          // InputSignal<Product>
  readonly disabled = input(false, { transform: booleanAttribute });      // accepts <app-product-card disabled>
  readonly max = input(10, { transform: numberAttribute });               // accepts max="5"
  readonly quantity = model(1);                                           // two-way: [(quantity)]
  readonly addToCart = output<{ productId: string; quantity: number }>();

  readonly total = computed(() => this.product().price * this.quantity());
}
<!-- in the parent's template -->
<app-product-card [product]="p" [(quantity)]="quantities[p.id]" disabled (addToCart)="cart.add($event)" />
  • input() returns a read-only signal: read it with product(). It works in templates, computed and effect, so derived values are just computed(() => ...) and you rarely need ngOnChanges.
  • input.required<T>() must be bound by the parent (a compile error otherwise). Reading it before Angular sets it, for example in the constructor, throws NG0950. Inputs are available from ngOnInit on, and always inside computed, effect and the template.
  • Transforms convert what the parent binds. Only bound values go through the transform, not the initial value. alias changes the public name: input(0, { alias: 'pageSize' }).
  • output<T>() returns an OutputEmitterRef<T> with emit(value). The parent listens with (addToCart)="...". It's no longer an RxJS EventEmitter; outputFromObservable(obs$) and outputToObservable(ref) convert when you need RxJS.
  • model() is a writable input. When the component calls quantity.set(...) it also emits quantityChange, which is what [(quantity)] listens to. A value set by the parent does not emit the event back.

Older code looks like this, and you'll see plenty of it:

import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core';

@Component({ selector: 'app-old-card', template: '' })
export class OldCard implements OnChanges {
  @Input({ required: true }) product!: { id: string; price: number };
  @Input() quantity = 1;
  @Output() quantityChange = new EventEmitter<number>();
  total = 0;

  ngOnChanges(changes: SimpleChanges): void {
    // recompute derived state by hand whenever an input changes
    this.total = this.product.price * this.quantity;
  }
}

ng generate @angular/core:signal-input-migration (and output-migration) convert decorators to the signal APIs.

Built-in control flow

@if (user(); as u) {
  <p>Welcome back, {{ u.name }}</p>
} @else if (loading()) {
  <app-spinner />
} @else {
  <a routerLink="/login">Sign in</a>
}

<ul>
  @for (item of items(); track item.id; let i = $index, last = $last) {
    <li [class.last]="last">{{ i + 1 }}. {{ item.name }}</li>
  } @empty {
    <li>Your cart is empty.</li>
  }
</ul>

@switch (order().status) {
  @case ('pending') { <app-badge tone="info">Pending</app-badge> }
  @case ('shipped') { <app-badge tone="ok">Shipped</app-badge> }
  @default { <app-badge>Unknown</app-badge> }
}
  • @if with as stores the condition's value in a variable, which also narrows its type (u is not null).
  • @for needs track. It tells Angular which item each row belongs to, so when the array changes it can keep, move, create or destroy rows instead of rebuilding the list. Use a stable id (track item.id). track $index reuses rows by position, which is fine for static lists of strings and wrong for lists you edit: delete the first row and every row's state shifts by one. track item (the object itself) breaks with immutable updates, because every updated item is a new object and its row is destroyed and recreated. Exercise 6 builds the tracking.
  • Implicit @for variables: $index, $count, $first, $last, $even, $odd. @empty renders when the list is empty.
  • @switch compares with === and has no fallthrough. @default is optional. Since Angular 21.1, consecutive @case blocks can share one body (@case ('paid') @case ('refunded') { ... }), and since 21.2 a final @default never; makes the type checker complain when a case is missing.

@defer lazy-loads part of a template. The components inside go into a separate JavaScript chunk that is fetched when the trigger fires:

@defer (on viewport; prefetch on idle) {
  <app-reviews [productId]="product().id" />
} @placeholder (minimum 300ms) {
  <p>Reviews</p>
} @loading (after 100ms; minimum 500ms) {
  <app-spinner />
} @error {
  <p>Could not load the reviews.</p>
}
  • Triggers: on idle (the default), on viewport, on interaction, on hover, on immediate, on timer(2s), and when condition. prefetch on ... downloads the code earlier than it renders it.
  • @placeholder shows before the trigger, @loading while the chunk downloads, and @error if it fails. after and minimum stop a spinner from flashing for a few milliseconds.
  • Only standalone components that aren't used anywhere else in the same file are deferred. If you also import Reviews elsewhere in the template, it ends up in the main bundle.
  • With server-side rendering, the server renders the @placeholder.

Older code uses *ngIf="user$ | async as user", *ngFor="let item of items; trackBy: trackById" and [ngSwitch] from CommonModule. ng generate @angular/core:control-flow migrates templates.

Content projection

A component can render content that its parent puts between its tags, the way React renders children:

import { Component } from '@angular/core';

@Component({
  selector: 'app-card',
  template: `
    <header><ng-content select="[card-title]" /></header>
    <section><ng-content /></section>
    <footer><ng-content select="app-card-actions, .actions">No actions</ng-content></footer>
  `,
})
export class Card {}
<app-card>
  <h2 card-title>Order #1042</h2>
  <p>3 items, shipped yesterday.</p>
  <app-card-actions><button>Track</button></app-card-actions>
</app-card>
  • Each top-level child of <app-card> goes to the first <ng-content> whose select matches it: a tag (h2), an attribute ([card-title]) or a class (.actions), or a comma-separated list of those. Anything that matches no slot goes to the <ng-content> without select. With no such slot, it isn't rendered at all.
  • Content between <ng-content> tags is the fallback, shown when nothing was projected there.
  • ngProjectAs makes an element match as something else, for example <ng-container ngProjectAs="[card-title]">...</ng-container>.
  • Projected content belongs to the parent. It's created even if the card hides that <ng-content> in an @if, and it's rendered at most once. To render content conditionally or repeatedly, pass an <ng-template> and render it with ngTemplateOutlet.
  • Query projected content with contentChild()/contentChildren(), and your own template with viewChild()/viewChildren(). They return signals.

Exercise 4 builds the slot matching.

The component lifecycle

WhenHookUse it for
class is createdconstructorinject() calls and field setup. Inputs aren't set yet.
a bound input changedngOnChanges(changes)reacting to input changes. It runs for signal inputs too, but computed is simpler there
first checkngOnInitone-time setup that needs inputs
every checkngDoCheckcustom change detection (rare)
projected content ready / checkedngAfterContentInit, ngAfterContentCheckedreading contentChild queries
own view ready / checkedngAfterViewInit, ngAfterViewCheckedreading viewChild queries
destroyedngOnDestroy, or inject(DestroyRef).onDestroy(fn)cleanup: subscriptions, timers, listeners

For a parent with one child, the first check runs in this order (ngOnChanges only runs for a component whose inputs are bound, so a root component never gets it):

Parent constructor, Child constructor
Parent ngOnChanges, ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked
  Child ngOnChanges, ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked
Parent ngAfterViewInit, ngAfterViewChecked

Init hooks go top-down, and a parent's view is only "done" after all its children are done. Exercise 5 builds the full order for a tree.

Modern code needs fewer hooks:

import { Component, DestroyRef, ElementRef, afterNextRender, computed, inject, input, viewChild } from '@angular/core';

@Component({ selector: 'app-chart', template: `<canvas #canvas></canvas>` })
export class Chart {
  readonly points = input.required<number[]>();
  readonly max = computed(() => Math.max(...this.points()));          // instead of ngOnChanges
  private readonly canvas = viewChild.required<ElementRef<HTMLCanvasElement>>('canvas');

  constructor() {
    afterNextRender(() => {
      // runs once in the browser after the first render (never during server-side rendering)
      const ctx = this.canvas().nativeElement.getContext('2d');
      console.log('chart ready', ctx !== null);
    });
    inject(DestroyRef).onDestroy(() => console.log('chart destroyed'));  // instead of ngOnDestroy
  }
}

afterNextRender and afterEveryRender (formerly afterRender) are the place for direct DOM work such as measuring or third-party widgets, because they only run in the browser.

Common mistakes

  • Reading a required input in the constructor (NG0950). Read it in computed, the template or ngOnInit.
  • Mutating inputs and arrays. this.items().push(x) changes nothing Angular can see: the array is the same reference, so pure pipes, OnPush children and signals don't update. Create a new array.
  • track $index on an editable list, or track item with immutable updates. Track a stable id.
  • Heavy methods in templates. Use computed, or a pure pipe.
  • Expecting @if around <ng-content> to skip creating the projected components. It only hides them.
  • Writing to the DOM in ngOnInit/ngAfterViewInit during SSR. Use afterNextRender.

How it looks in a real codebase

Side note
  • Container and presentational components. Containers (routed pages) inject services and hold state. Presentational components only get input()s and emit output()s, use OnPush, and are easy to reuse and test.
  • Tests create the component with TestBed.createComponent(ProductCard), set inputs with fixture.componentRef.setInput('product', p), and wait with await fixture.whenStable().
  • strictTemplates type-checks templates: a wrong input type, a missing required input or a typo in a property is a build error.
ReactAngular
propsinput()
callback props (onChange)output()
controlled value + onChangemodel() with [(value)]
children, named slots as props<ng-content>, <ng-content select>
{cond && <X />}, .map() with key@if, @for with track
React.lazy + Suspense@defer with @placeholder/@loading
useEffect cleanupDestroyRef.onDestroy, takeUntilDestroyed()

The exercises

  1. Attribute transforms: booleanAttribute and numberAttribute, for inputs written as plain HTML attributes.
  2. Pure pipes: memoize by reference and see why mutating an array leaves a pipe's output stale.
  3. Signal inputs, outputs and model(): build input, input.required, output and model, plus the binding code the compiler generates.
  4. Content projection: match projected children to <ng-content select> slots, with ngProjectAs.
  5. Lifecycle order: produce the exact hook order for a component tree, first check and later checks.
  6. @for and track: reuse rows by key, keep the implicit variables right, and move as few rows as possible.
  7. A control-flow renderer: render @if, @for, @switch and @let from a small template tree with proper scoping.

Practise this lesson

In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app