Counter stuck at 0 after an OnPush refactor
Solution idea
inc() adds 1 to stats.count in place, so the object bound to [stats] is the same reference after every click. Angular checks an OnPush component only when an input receives a new value (compared by reference), when an event fires in its own template, or when a signal its template reads changes. The mutation meets none of these: the stats input signal keeps the same object, so Angular skips CounterDisplayComponent and the paragraph keeps its first render while the real count grows.
Solution
Overview
inc() adds 1 to stats.count in place, so the object bound to [stats] is the same reference after every click. Angular checks an OnPush component only when an input receives a new value (compared by reference), when an event fires in its own template, or when a signal its template reads changes. The mutation meets none of these: the stats input signal keeps the same object, so Angular skips CounterDisplayComponent and the paragraph keeps its first render while the real count grows.
Replace the object instead of changing it: this.stats = { ...this.stats, count: this.stats.count + 1 } gives the binding a new reference, the input updates and the display renders the new count. Passing the number itself ([count]="stats.count") or keeping the count in a signal works too. Turning OnPush off would hide the bug and bring back the work the refactor removed.
Files
<!doctype html><html><head><meta charset="utf-8"><title>UF</title><base href="/"/></head><body><app-root></app-root></body></html>import 'zone.js';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent);
button {
padding: .5rem 1rem;
border-radius: .5rem;
}
<button (click)="inc()">Increment</button>
<app-counter-display [stats]="stats" />
import { Component } from '@angular/core';
import { CounterDisplayComponent } from './counter-display.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [CounterDisplayComponent],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
stats = { count: 0 };
inc() {
// OnPush compares input references, so hand the display a new object.
this.stats = { ...this.stats, count: this.stats.count + 1 };
}
}
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
@Component({
selector: 'app-counter-display',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<p>{{ stats().count }}</p>'
})
export class CounterDisplayComponent {
readonly stats = input.required<{ count: number }>();
}
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.