Sub topic 2
How Templates React to Signals: OnPush and Zoneless
This chapter assumes you know how to build Angular components, use data binding, and have a basic picture of change detection. You should also be comfortable with signal() and computed() from the previous chapter.
How Templates React to Signals
When a template calls a signal, such as {{ count() }}, Angular records that signal as a dependency of the component's view. Later, when the signal changes, Angular marks that view for checking. It does not need to check the whole component tree.
This works well with ChangeDetectionStrategy.OnPush. A signal change marks an OnPush component as dirty, so you don't need markForCheck(). Signals also make zoneless apps possible. A zoneless app runs without Zone.js. Instead of patching browser events, Angular schedules change detection when a signal that a template reads changes.
import { bootstrapApplication } from '@angular/platform-browser';
import { provideZonelessChangeDetection } from '@angular/core';
import { AppComponent } from './app.component';
bootstrapApplication(AppComponent, {
providers: [provideZonelessChangeDetection()],
});Signal Inputs, model(), and output()
A component's public API can be built from signals:
input()declares an input as a read-only signal, optionally with a default value.input.required()makes the parent provide a value.model()declares a writable input. When the child callsset()on it, the new value goes back to the parent.output()declares an event that the child fires withemit().
import { ChangeDetectionStrategy, Component, computed, input, model, output } from '@angular/core';
@Component({
selector: 'app-rating',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<span>{{ label() }}</span>
@for (star of stars(); track star) {
<button (click)="value.set(star)">{{ star <= value() ? '★' : '☆' }}</button>
}
<button (click)="submitted.emit(value())">Submit</button>
`,
})
export class RatingComponent {
label = input.required<string>();
max = input(5);
value = model(0);
submitted = output<number>();
stars = computed(() => Array.from({ length: this.max() }, (_, i) => i + 1));
}The parent uses banana-in-a-box syntax, [( )], for the model. score can be a plain property or a writable signal:
<app-rating label="Quality" [max]="10" [(value)]="score" (submitted)="save($event)" />A common mistake is calling this.max.set(...) inside the child. Signal inputs are read-only, so this does not compile. Use model() when the child must write the value.
Exercise
A child component needs to change a selected value and have the parent's bound signal update too. Should you declare it with input() or model(), and how does the parent bind it?
Show answer
Use model(), because input() signals are read-only. The parent binds with [(selected)]="mySignal".