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.
In short
- Standalone components list what the template uses in
imports input(),output()andmodel()are the component's API- Data flows down with
[ ], events flow up with( ) @if,@forwithtrack 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: trueany more). A component lists what its template uses inimports. Forget one and the compiler says'app-x' is not a known element(NG8001). selectoris how other templates use it:<app-cart-line [item]="line" (removed)="remove($event)" />. Self-closing tags work for components.template/templateUrlandstyles/styleUrl. Styles are scoped to the component by default, and:hoststyles the component's own element.- The app starts with
bootstrapApplication(App, appConfig), whereappConfig.providersholds app-wide setup (provideRouter(routes),provideHttpClient()). There's no root module. - New projects (Angular 20 style guide) name files
cart-line.ts,cart-line.htmland the classCartLine. Older code usescart-line.component.tsandCartLineComponent. 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
| Syntax | What it does | Example |
|---|---|---|
{{ 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" |
#ref | template reference to an element or component | <input #q (keyup.enter)="search(q.value)"> |
@let | a local template variable | @let total = cart.total(); |
value | pipe: arg | formats 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; acomputedsignal runs only when its inputs change. - Properties vs attributes.
[value]="name"sets thevalueproperty, 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'', andsize="3"passes'3'. That's why inputs often use thebooleanAttributeandnumberAttributetransforms (exercise 1). - Interpolation turns
nullandundefinedinto an empty string and everything else intoString(value):
// 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
transformagain only when an argument changes by reference. Push an item into an array and a purefilterpipe keeps showing the old result. Exercise 2 builds this. - Event bindings run a statement.
$eventis 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 withproduct(). It works in templates,computedandeffect, so derived values are justcomputed(() => ...)and you rarely needngOnChanges.input.required<T>()must be bound by the parent (a compile error otherwise). Reading it before Angular sets it, for example in the constructor, throwsNG0950. Inputs are available fromngOnIniton, and always insidecomputed,effectand the template.- Transforms convert what the parent binds. Only bound values go through the transform, not the initial value.
aliaschanges the public name:input(0, { alias: 'pageSize' }). output<T>()returns anOutputEmitterRef<T>withemit(value). The parent listens with(addToCart)="...". It's no longer an RxJSEventEmitter;outputFromObservable(obs$)andoutputToObservable(ref)convert when you need RxJS.model()is a writable input. When the component callsquantity.set(...)it also emitsquantityChange, 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> }
}
@ifwithasstores the condition's value in a variable, which also narrows its type (uis notnull).@forneedstrack. 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 $indexreuses 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
@forvariables:$index,$count,$first,$last,$even,$odd.@emptyrenders when the list is empty. @switchcompares with===and has no fallthrough.@defaultis optional. Since Angular 21.1, consecutive@caseblocks 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), andwhen condition.prefetch on ...downloads the code earlier than it renders it. @placeholdershows before the trigger,@loadingwhile the chunk downloads, and@errorif it fails.afterandminimumstop 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
Reviewselsewhere 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>whoseselectmatches 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>withoutselect. With no such slot, it isn't rendered at all. - Content between
<ng-content>tags is the fallback, shown when nothing was projected there. ngProjectAsmakes 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 withngTemplateOutlet. - Query projected content with
contentChild()/contentChildren(), and your own template withviewChild()/viewChildren(). They return signals.
Exercise 4 builds the slot matching.
The component lifecycle
| When | Hook | Use it for |
|---|---|---|
| class is created | constructor | inject() calls and field setup. Inputs aren't set yet. |
| a bound input changed | ngOnChanges(changes) | reacting to input changes. It runs for signal inputs too, but computed is simpler there |
| first check | ngOnInit | one-time setup that needs inputs |
| every check | ngDoCheck | custom change detection (rare) |
| projected content ready / checked | ngAfterContentInit, ngAfterContentChecked | reading contentChild queries |
| own view ready / checked | ngAfterViewInit, ngAfterViewChecked | reading viewChild queries |
| destroyed | ngOnDestroy, 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 incomputed, the template orngOnInit. - Mutating inputs and arrays.
this.items().push(x)changes nothing Angular can see: the array is the same reference, so pure pipes,OnPushchildren and signals don't update. Create a new array. track $indexon an editable list, ortrack itemwith immutable updates. Track a stable id.- Heavy methods in templates. Use
computed, or a pure pipe. - Expecting
@ifaround<ng-content>to skip creating the projected components. It only hides them. - Writing to the DOM in
ngOnInit/ngAfterViewInitduring SSR. UseafterNextRender.
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 emitoutput()s, useOnPush, and are easy to reuse and test. - Tests create the component with
TestBed.createComponent(ProductCard), set inputs withfixture.componentRef.setInput('product', p), and wait withawait fixture.whenStable(). strictTemplatestype-checks templates: a wrong input type, a missing required input or a typo in a property is a build error.
| React | Angular |
|---|---|
| props | input() |
callback props (onChange) | output() |
controlled value + onChange | model() 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 cleanup | DestroyRef.onDestroy, takeUntilDestroyed() |
The exercises
- Attribute transforms:
booleanAttributeandnumberAttribute, for inputs written as plain HTML attributes. - Pure pipes: memoize by reference and see why mutating an array leaves a pipe's output stale.
- Signal inputs, outputs and model(): build
input,input.required,outputandmodel, plus the binding code the compiler generates. - Content projection: match projected children to
<ng-content select>slots, withngProjectAs. - Lifecycle order: produce the exact hook order for a component tree, first check and later checks.
@forand track: reuse rows by key, keep the implicit variables right, and move as few rows as possible.- A control-flow renderer: render
@if,@for,@switchand@letfrom 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