Angular components and templates: the basics
Everything you see in an Angular app is a tree of components, and each component’s template decides what that piece of the screen shows. This page builds the order list of OrdersPortal, an invented order-management app, and introduces the building blocks in the order you need them: the component itself, its template syntax, data binding, directives, pipes and the lifecycle hooks Angular calls along the way.
The samples target Angular 22, where components are standalone and OnPush by default, inputs and outputs are usually declared with the signal-based input(), output() and model() functions, and templates use built-in control flow (@if, @for). Every sample on this page was compiled with ngc from @angular/compiler-cli 22.2.6 (TypeScript 6.0.3, strictTemplates on) and rendered with renderApplication() from @angular/platform-server on Node.js 22; the outputs shown are what that render produced, with Angular’s internal attributes removed.
Topics on this page
Section titled “Topics on this page”| Topic | Use it for |
|---|---|
| Components | A class plus a template that owns one piece of the UI |
| Templates | HTML with interpolation, control flow and local variables |
| Data binding | Moving data between the class and the DOM, in both directions |
| Directives | Adding behavior to existing elements |
| Pipes | Formatting values for display inside templates |
| Lifecycle hooks | Running code when a component is created, changed or destroyed |
Components
Section titled “Components”A component is a TypeScript class decorated with @Component. The decorator supplies a selector (the custom element name, such as app-order-card), a template (inline with template or in a file with templateUrl), optional styles, and an imports array listing every component, directive and pipe the template uses. Components are standalone by default since Angular 19, so there is no module to declare them in.
A component talks to its parent through inputs and outputs. input() and input.required() create read-only signals that the parent sets with property binding; output() creates an emitter the parent listens to with event binding. Derived values belong in computed(), which recalculates only when the signals it reads change. Members used only by the template should be protected, as the style guide recommends.
Since Angular 22 a component without an explicit changeDetection is OnPush: Angular re-renders it when an input changes, an event fires inside it, or a signal it reads changes. That is why the samples keep state in signals.
export interface Order { id: number; customer: string; total: number; placedOn: Date; status: 'pending' | 'shipped' | 'cancelled';}
// order-card.tsimport { Component, computed, input, output } from '@angular/core';import { CurrencyPipe, DatePipe } from '@angular/common';import { Order } from './order';import { OrderStatusPipe } from './order-status.pipe';import { HighlightOverdue } from './highlight-overdue';
@Component({ selector: 'app-order-card', imports: [CurrencyPipe, DatePipe, OrderStatusPipe, HighlightOverdue], template: ` <article [appHighlightOverdue]="order().placedOn" [class.cancelled]="isCancelled()"> <h3>Order #{{ order().id }} for {{ order().customer }}</h3> <p>{{ order().total | currency: 'USD' }} placed {{ order().placedOn | date: 'yyyy-MM-dd' : 'UTC' }}</p> <p>Status: {{ order().status | orderStatus }}</p> @if (!isCancelled()) { <button type="button" [attr.aria-label]="'Cancel order ' + order().id" (click)="cancel.emit(order().id)"> Cancel </button> } </article> `,})export class OrderCard { readonly order = input.required<Order>(); readonly cancel = output<number>(); protected readonly isCancelled = computed(() => this.order().status === 'cancelled');}The rendered output of this card appears under Templates, where the parent list uses it.
Pitfalls:
- Mutating an input object.
order()returns the parent’s object. Changing its fields from the child creates two owners of the same state; emit an output and let the parent replace the object. - Missing
imports. If the template uses| currencyor another component, the class must list it inimports, or compilation fails with an unknown element or pipe error. - Plain fields under
OnPush. Updating a non-signal field from a timer or a promise callback does not refresh the view in Angular 22. Use a signal, or setChangeDetectionStrategy.Eageronly while migrating old code.
Templates
Section titled “Templates”A template is HTML plus Angular syntax. {{ expression }} interpolates text. Built-in control flow blocks decide what is rendered: @if / @else if / @else, @for with a required track expression and an optional @empty block, and @switch / @case. @let declares a read-only local variable, and #name declares a template reference variable that points at an element or directive. @defer lazily loads part of a template and has its own page in the features section.
Control flow replaced the *ngIf, *ngFor and *ngSwitch structural directives, which were deprecated in Angular 20. You will still read them in older code; ng generate @angular/core:control-flow migrates them.
Template expressions should stay simple: read signals, call cheap methods, format with pipes. Branching business rules belong in the class, usually as a computed().
// orders-page.ts: the parent listimport { Component, signal } from '@angular/core';import { Order } from './order';import { OrderCard } from './order-card';
@Component({ selector: 'app-root', imports: [OrderCard], template: ` <h2>Open orders ({{ orders().length }})</h2> @let pending = pendingCount(); <p>{{ pending }} pending</p> @for (order of orders(); track order.id) { <app-order-card [order]="order" (cancel)="cancelOrder($event)" /> } @empty { <p>No orders yet.</p> } `,})export class OrdersPage { protected readonly orders = signal<Order[]>([ { id: 1001, customer: 'Harbor Bikes', total: 249.5, placedOn: new Date('2026-11-02T09:00:00Z'), status: 'pending' }, { id: 1002, customer: 'Maple Cafe', total: 80, placedOn: new Date('2026-11-17T14:30:00Z'), status: 'shipped' }, ]);
protected pendingCount(): number { return this.orders().filter((o) => o.status === 'pending').length; }
cancelOrder(id: number): void { this.orders.update((list) => list.map((o) => (o.id === id ? { ...o, status: 'cancelled' } : o))); }}Rendered output (with the date fixed at 2026-11-18 for the overdue check):
<app-root><h2>Open orders (2)</h2><p>1 pending</p><app-order-card><article class="overdue"><h3>Order #1001 for Harbor Bikes</h3><p>$249.50 placed 2026-11-02</p><p>Status: Awaiting dispatch</p><button type="button" aria-label="Cancel order 1001"> Cancel </button></article></app-order-card><app-order-card><article class=""><h3>Order #1002 for Maple Cafe</h3><p>$80.00 placed 2026-11-17</p><p>Status: On its way</p><button type="button" aria-label="Cancel order 1002"> Cancel </button></article></app-order-card></app-root>Pitfalls:
- A poor
trackexpression.track $indexmakes Angular reuse DOM by position, so inserting at the top re-renders every row and can move focus or input state to the wrong item. Track a stable id. - Logic-heavy expressions. A nested ternary in the template runs on every check and cannot be unit-tested on its own. Move it to a
computed(). - Expecting
@letto be assignable.@letvalues are read-only and are re-evaluated when their inputs change; to change state, update the signal they read.
Data binding
Section titled “Data binding”Data binding connects the class to the DOM. Interpolation ({{ order().id }}) writes text. Property binding ([order]="order", [disabled]="busy()") sets a DOM property or a component input from an expression. Attribute binding ([attr.aria-label]) sets an HTML attribute that has no matching property, which is common for ARIA. Class and style binding ([class.cancelled]="isCancelled()", [style.width.px]="w") toggle a single class or style. Event binding ((click)="save()", (cancel)="cancelOrder($event)") runs a statement when the DOM or a child output emits; $event holds the payload.
Two-way binding uses the “banana in a box” syntax [(value)]. On a component it pairs with model(), a writable input whose changes flow back to the parent’s signal. On form controls, [(ngModel)] from FormsModule does the same for template-driven forms.
// quantity-stepper.ts: two-way binding with model()import { Component, input, model, signal } from '@angular/core';
@Component({ selector: 'app-quantity', template: ` <button type="button" (click)="quantity.set(quantity() - 1)" [disabled]="quantity() <= 1">-</button> <span>{{ quantity() }}</span> <button type="button" (click)="quantity.set(quantity() + 1)">+</button> `,})export class QuantityStepper { readonly productId = input.required<string>(); readonly quantity = model(1);}
@Component({ selector: 'app-cart-line', imports: [QuantityStepper], template: `<app-quantity productId="SKU-42" [(quantity)]="cartQuantity" /> <p>In cart: {{ cartQuantity() }}</p>`,})export class CartLine { protected readonly cartQuantity = signal(3);}Rendered, the cart line shows <p>In cart: 3</p>, and each click on a stepper button updates cartQuantity in the parent.
Pitfalls:
- Missing brackets.
src="avatarUrl"sets the literal textavatarUrl;[src]="avatarUrl"evaluates the expression. Static strings such asproductId="SKU-42"are fine without brackets. - Binding to an attribute as if it were a property.
[aria-label]fails because there is no such DOM property; use[attr.aria-label]. - Calling a signal setter in the template on every check. Event handlers may set signals; property bindings must not, or you create an update loop.
Directives
Section titled “Directives”A directive adds behavior to an element without owning a template. Angular has three kinds: components (directives with a template), attribute directives that change how an existing element looks or behaves, and structural directives that add or remove DOM (*ngIf historically; control flow blocks now cover most cases). Built-in attribute directives include NgClass, NgStyle and the forms directives, but the style guide prefers plain [class] and [style] bindings over NgClass and NgStyle.
A custom attribute directive is a class with @Directive and an attribute selector. It takes inputs like a component and changes its host element through the host metadata, which the Angular docs recommend over the @HostBinding and @HostListener decorators (kept for backward compatibility). An input named after the selector lets you write [appHighlightOverdue]="value".
import { Directive, computed, input } from '@angular/core';
const DAY_MS = 24 * 60 * 60 * 1000;
@Directive({ selector: '[appHighlightOverdue]', host: { '[class.overdue]': 'isOverdue()' },})export class HighlightOverdue { readonly appHighlightOverdue = input.required<Date>(); // the order date readonly maxAgeDays = input(7); readonly now = input(new Date('2026-11-18T00:00:00Z')); // fixed for a reproducible sample
protected readonly isOverdue = computed( () => this.now().getTime() - this.appHighlightOverdue().getTime() > this.maxAgeDays() * DAY_MS, );}In the rendered list above, order 1001 (16 days old) got class="overdue" and order 1002 did not.
Pitfalls:
- Touching the DOM directly. Reaching for
ElementRef.nativeElement.stylebreaks server rendering and bypasses Angular’s sanitization; prefer host bindings. - Using a component where a directive would do. If you only add behavior to an existing
<button>or<input>, a directive keeps native semantics and accessibility; wrapping it in a component hides them. - Selector collisions. Since Angular 22, an element matched by multiple components is a compile-time error. Prefix selectors (
app-,op-) consistently.
A pipe transforms a value for display with {{ value | pipeName: arg }}. Angular ships DatePipe, CurrencyPipe, DecimalPipe, PercentPipe, UpperCasePipe, LowerCasePipe, TitleCasePipe, SlicePipe, JsonPipe, KeyValuePipe and AsyncPipe in @angular/common; import the ones a template uses. Pipes take arguments after colons, for example date: 'yyyy-MM-dd' : 'UTC' for a format and a time zone.
Pipes are pure by default: Angular calls transform() again only when the input value or object reference changes. That makes them cheap to call in templates. An impure pipe (pure: false) runs on every check and should be rare.
import { Pipe, PipeTransform } from '@angular/core';import { Order } from './order';
const labels: Record<Order['status'], string> = { pending: 'Awaiting dispatch', shipped: 'On its way', cancelled: 'Cancelled',};
@Pipe({ name: 'orderStatus' })export class OrderStatusPipe implements PipeTransform { transform(status: Order['status']): string { return labels[status]; }}In the rendered output, pending became Awaiting dispatch, 249.5 | currency: 'USD' became $249.50, and the dates were formatted in UTC.
Pitfalls:
- Mutating an array that a pure pipe reads.
items.push(x)keeps the same reference, so a pure filter or sort pipe does not re-run. Replace the array ([...items, x]), or better, derive the list withcomputed(). - Forgetting the time zone.
DatePipeformats in the browser’s zone by default, so server-rendered and client-rendered dates can differ; pass a zone when it matters. - Heavy work in pipes. A pipe that sorts thousands of rows runs whenever its input reference changes; do expensive work once in a service or a
computed().
Lifecycle hooks
Section titled “Lifecycle hooks”Angular calls optional hook methods as it creates, updates and destroys a component. The constructor runs first, but inputs are not set yet, so keep it to dependency injection. ngOnChanges(changes) runs before ngOnInit and whenever an input changes, with a SimpleChanges map. ngOnInit() runs once after the first inputs are set and is the usual place to start work that needs them. ngOnDestroy() runs before the component is removed. ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit and ngAfterViewChecked exist for content and view queries and are needed less often.
Modern code needs fewer hooks: computed() replaces most ngOnChanges logic, effect() reacts to signal changes, inject(DestroyRef).onDestroy() registers cleanup from anywhere in the injection context, and afterNextRender() runs browser-only DOM work after rendering.
// The QuantityStepper from Data binding, instrumented with hooks (fragment)export class QuantityStepper implements OnChanges, OnInit, OnDestroy { readonly productId = input.required<string>(); readonly quantity = model(1);
constructor() { console.log('constructor: productId not set yet'); inject(DestroyRef).onDestroy(() => console.log('DestroyRef.onDestroy callback')); } ngOnChanges(changes: SimpleChanges): void { console.log('ngOnChanges:', Object.keys(changes).join(', ')); } ngOnInit(): void { console.log('ngOnInit: productId =', this.productId()); } ngOnDestroy(): void { console.log('ngOnDestroy'); }}Output when the cart line is rendered and then destroyed:
constructor: productId not set yetngOnChanges: productId, quantityngOnInit: productId = SKU-42ngOnDestroyDestroyRef.onDestroy callbackPitfalls:
- Reading inputs in the constructor. A required signal input throws if read before it is set; a decorator
@Input()is simplyundefined. Move that code tongOnInitor acomputed(). - Leaking subscriptions. A manual
subscribe()inngOnInitkeeps running after the component is gone unless you clean up; usetakeUntilDestroyed(), theasyncpipe ortoSignal(). - DOM work in
ngOnInit. The view does not exist yet and the code also runs during server rendering; useafterNextRender()for measurements and third-party widgets.
Choosing between them
Section titled “Choosing between them”- Build UI as small components with signal inputs and outputs; keep state in the nearest common parent.
- Use control flow for structure, bindings for data, an attribute directive for reusable behavior on existing elements, and a pipe only for display formatting.
- Reach for a lifecycle hook last:
computed(),effect()andDestroyRefcover most cases more directly.
Interview questions
Section titled “Interview questions”What is the difference between input() and @Input()?
input() returns a read-only signal, so reading it in a computed() or template tracks changes automatically, and input.required() makes the binding mandatory at compile time. @Input() is a decorated plain property that relies on ngOnChanges or setters to react to changes. Both are supported; new code uses input().
Why does @for require track?
Angular uses the track expression to match items between renders and reuse their DOM. Without a stable key it would destroy and recreate rows, losing focus, animations and form state, and doing more DOM work.
What does OnPush by default mean for existing code moving to Angular 22?
Components without an explicit strategy re-render only on input changes, events inside them, or signal changes. Code that mutated plain fields from timers or callbacks may stop updating. The fix is to use signals, or temporarily set ChangeDetectionStrategy.Eager on those components.
When would you write a directive instead of a component? When you add behavior to an element that already exists, such as highlighting, tooltips or input masks, and want to keep the element’s native semantics. A component is for owning a template.
Senior scenario: OrdersPortal’s order list is slow with 2,000 rows and loses focus while editing. What do you check?
First the @for track expression: tracking by index or by object identity after reloading data causes full re-renders and moved focus, so track order.id. Then look for impure pipes or method calls in bindings that do heavy work on every check and move them to computed(). Make sure components are OnPush and state lives in signals so only changed rows update. If the list is still large, page or virtualize it (the CDK virtual scroll) and defer below-the-fold sections with @defer.
Related pages
Section titled “Related pages”- Project setup: the CLI and files these components live in.
- Services, HTTP, routing and forms: where the order data comes from.
- Signals and change detection
- Control flow, templates and pipes in depth
- Input properties and host binding