Open this for the concrete recipe once the profiler has named the bucket. Verified 2026-09 against https://material.angular.dev/cdk/scrolling/overview, https://angular.dev/api/core/afterNextRender and https://angular.dev/guide/zoneless.
1. CDK virtual scroll
import { Component, ChangeDetectionStrategy, input } from '@angular/core';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { OrderRow } from './order-row';
import type { Order } from '../model/order';
@Component({
selector: 'app-order-list',
imports: [ScrollingModule, OrderRow],
changeDetection: ChangeDetectionStrategy.OnPush,
styles: `cdk-virtual-scroll-viewport { height: 70vh; }`,
template: `
<cdk-virtual-scroll-viewport itemSize="48">
<app-order-row *cdkVirtualFor="let order of orders(); trackBy: byId" [order]="order" />
</cdk-virtual-scroll-viewport>`,
})
export class OrderList {
readonly orders = input.required<readonly Order[]>();
protected byId = (_: number, order: Order) => order.id;
}
itemSizemust match the rendered row height, or the scrollbar drifts and rows flicker. Fix the row height in CSS; it is worth the design conversation.*cdkVirtualForis a structural directive, so it is one of the few placestrackBy(not@for … track) is still the syntax.- Variable-height rows need
autosizefrom@angular/cdk-experimental/scrolling; it is slower and less stable, so prefer a fixed height. - The viewport needs a bounded height. A viewport inside a growing container renders everything and the whole exercise is wasted.
Prefer server pagination. Virtual scroll fixes the DOM cost but not the payload, the JSON parse or the memory. Ten thousand rows over the wire is a network problem wearing a rendering costume.
2. Large tables
| Pressure | Move |
|---|---|
| Many rows | Server-side pagination first; CDK virtual scroll if the data must be local |
| Many columns | Render only the visible column set; horizontal virtualisation is rarely worth its complexity |
| Sorting/filtering feels slow | Do it on the server. MatTableDataSource sorts and filters the whole array on the main thread on every keystroke |
| Every row re-renders on one cell change | Row is its own OnPush component taking a prepared view-model input(), so a changed reference touches one row |
| Inline editing | Keep the edited row's state in the row component; do not lift it into a shared signal that every row reads |
Precompute the row view model once, in a computed() over the source array, so the template does no formatting:
protected readonly rows = computed(() =>
this.orders().map((o) => ({ id: o.id, number: o.number, total: this.money.format(o.total), overdue: !o.paid })));
3. Debounce without lag
import { Component, ChangeDetectionStrategy, signal } from '@angular/core';
import { toSignal, toObservable } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged } from 'rxjs';
@Component({ /* … */ changeDetection: ChangeDetectionStrategy.OnPush })
export class OrderFilter {
readonly text = signal(''); // echoes the keystroke immediately
readonly debounced = toSignal(
toObservable(this.text).pipe(debounceTime(300), distinctUntilChanged()),
{ initialValue: '' },
); // drives the query
}
Binding the input to the debounced value instead makes typing feel broken; the split above keeps the field responsive while the expensive consumer waits.
4. DOM measurement
import { Component, ElementRef, afterNextRender, inject, signal } from '@angular/core';
@Component({ /* … */ })
export class Sticky {
private readonly host = inject(ElementRef<HTMLElement>);
protected readonly height = signal(0);
constructor() {
afterNextRender({ read: () => this.height.set(this.host.nativeElement.offsetHeight) });
}
}
afterNextRenderruns once;afterEveryRenderruns after each render.afterRenderwas renamed in v20 and no longer exists, so code using it does not compile on supported versions.- Phases are the object keys —
earlyRead,write,mixedReadWrite,read— and they batch all components' reads before all writes, which is what avoids layout thrash. There is noAfterRenderPhaseenum any more. - Both are browser-only: they do not run during server rendering, which makes them the correct home for
window/documentwork. - Never
setTimeout(0)for this. It runs at an unrelated moment and reintroduces the thrash the phases exist to prevent.
5. Off the main thread
ng generate web-worker sorting
Worth it for sorting or transforming tens of thousands of records, parsing large CSV/JSON, crypto, and image manipulation. Not worth it for anything under a few milliseconds — the structured-clone cost of the payload can exceed the work. Measure the round trip before keeping it; transfer ArrayBuffers rather than object graphs where you can.
6. CSS-level wins
content-visibility: autowithcontain-intrinsic-size: <approx height>on long off-screen sections skips their layout and paint until they approach the viewport. The intrinsic size is required, or the scrollbar jumps.will-changeonly on an element that is actively animating, and removed afterwards — each one costs a compositor layer and memory.- Avoid
ViewEncapsulation.Nonewith deep selectors: the style becomes global and every DOM change triggers a wider style recalculation. - Reserve space for images, ads and late-loading widgets (
width/height,aspect-ratio, or a sized@placeholder) — this is the whole of CLS.
7. Zone-only escape hatches
These apply only while zone.js is still loaded (v20 apps that have not opted in to zoneless, or older codebases):
NgZone.runOutsideAngular(() => …)forscroll,mousemove,requestAnimationFrameloops and third-party widgets, re-entering withngZone.run()only when state must update.- After removing
zone.js, delete these calls: outside a zone they are a no-op with a misleading name, and they hide the fact that the notification now has to come from a signal write, a listener ormarkForCheck().