Sub topic 3
Signals and OnPush
Assume you know Angular components, inputs, templates, and basic Observables. You also need to know that JavaScript objects are passed by reference.
Signals and OnPush
A signal is a reactive value that records which templates read it. When its value changes, Angular marks those templates for refresh. This works with OnPush; you usually do not need to call markForCheck().
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<p>Count: {{ count() }}</p>
<button (click)="increment()">Add</button>
`,
})
export class CounterComponent {
count = signal(0);
increment() {
this.count.update((value) => value + 1);
}
}The template reads count() and becomes dependent on that signal. The update() call changes the signal and schedules the component for checking.
Stale views and debugging
An OnPush view can become stale when Angular has no reason to check it.
Common causes include:
- Mutating an input object instead of replacing it.
- Updating a plain field inside a manual subscription without calling
markForCheck(). - Changing data outside an Angular event, signal, or other known trigger.
- Expecting
detectChanges()to update unrelated components.
Start debugging by checking the data flow. Confirm that an input has a new object reference, then confirm that the update occurs inside a recognized trigger. Use the Angular DevTools component tree to inspect inputs and component state.
Testing OnPush components
Tests should set inputs through the component reference, then run change detection. setInput() also informs Angular that the input changed.
const fixture = TestBed.createComponent(UserCardComponent);
fixture.componentRef.setInput('user', { name: 'Ada' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Ada');For signal-based components, change the signal, call fixture.detectChanges() when needed by the test environment, and assert on the rendered DOM rather than only on the component field.
OnPush in zoneless Angular
Zone.js traditionally notices asynchronous activity and starts a change-detection pass. Zoneless Angular removes that global notification mechanism. Applications must use explicit notifications such as signal updates, input changes, template events, or framework APIs.
OnPush remains useful because it limits unnecessary checks. Signals become especially important in zoneless applications because they both hold state and notify Angular when a template needs updating.
Exercise
An OnPush child displays an old user name after the parent changes user.name. What should the parent do?
Show answer
Replace the object, for example user = { ...user, name: 'Grace' }, so the child receives a new reference.