Angular Performance
Why this matters
Section titled “Why this matters”Performance work goes wrong in a predictable way: someone reads that OnPush and trackBy make Angular faster, applies both everywhere, and the application is exactly as slow as before — because the actual cost was a 4 MB unoptimised hero image and an eagerly-loaded charting library.
The discipline that separates useful performance work from cargo cult is measure, then fix the largest measured cost, then measure again. Everything below assumes that loop.
Two kinds of performance
Section titled “Two kinds of performance”They have different causes, different tools, and different fixes. Conflating them is the first mistake.
Loading performance — how fast the application becomes visible and interactive. Governed by bytes shipped, request waterfalls, and how much work happens before first paint. Shows up as Largest Contentful Paint and Time to First Byte.
Runtime performance — how responsive it feels afterwards. Governed by how often change detection runs and how expensive each pass is. Shows up as Interaction to Next Paint and dropped frames.
| Loading | Runtime | |
|---|---|---|
| Measured by | LCP, TTFB, bundle size | INP, frame timing, CD duration |
| Tools | Lighthouse, bundle analyser, network panel | Angular DevTools profiler, Chrome Performance panel |
| Main levers | Lazy routes, @defer, images, SSR |
Zoneless, OnPush, signals, track, virtual scroll |
Measure first
Section titled “Measure first”Lighthouse for the load, in an incognito window with throttling on. Numbers from a warm cache on a fast laptop are fiction.
Angular DevTools profiler for runtime. Record, interact, read the timeline. Each bar is a change-detection pass, labelled with what triggered it. A wall of bars while the page is idle is zone pollution. One tall bar is a slow computation — click it for the per-component breakdown of template evaluation versus lifecycle hooks.
Chrome DevTools’ Angular track shows Angular-specific data alongside the browser’s own profiling, with flame charts covering component rendering, change-detection cycles and lifecycle hooks.
Bundle analysis to find what is actually in your JavaScript:
ng build --stats-jsonnpx esbuild-visualizer --metadata dist/<app>/stats.jsonThe usual finding is a date library, an icon set, or a chart package imported eagerly from a shared module.
Budgets in angular.json turn all of this into something CI enforces rather than something someone remembers:
"budgets": [ { "type": "initial", "maximumWarning": "500kB", "maximumError": "800kB" }, { "type": "anyComponentStyle", "maximumWarning": "4kB" }]A budget that fails the build is worth more than a performance audit nobody repeats.
Loading performance
Section titled “Loading performance”Lazy-loaded routes
Section titled “Lazy-loaded routes”The highest-leverage change in almost every application, and nearly free:
export const routes: Routes = [ { path: '', component: Home }, { path: 'orders', loadChildren: () => import('./orders/orders.routes').then((m) => m.ordersRoutes), }, { path: 'admin', canMatch: [isAdmin], loadChildren: () => import('./admin/admin.routes').then((m) => m.adminRoutes), },];Note canMatch rather than canActivate on the gated route: canMatch runs during route matching, before the chunk is fetched, so an unauthorised user never downloads the admin bundle. canActivate downloads it and then refuses.
Feature boundaries are the right granularity. Finer splitting usually costs more in requests than it saves in bytes.
@defer
Section titled “@defer”@defer moves code out of the initial bundle at the template level rather than the route level:
@defer (on viewport) { <revenue-chart [data]="chartData()" />} @placeholder (minimum 500ms) { <div class="chart-skeleton"></div>} @loading (after 100ms; minimum 1s) { <spinner />} @error { <p>The chart could not be loaded.</p>}Two conditions must hold for dependencies inside a @defer block to actually be deferred:
- They must be standalone. Non-standalone dependencies load eagerly regardless.
- They must not be referenced outside the block in the same file — including from a
ViewChildquery. One stray reference and the whole thing loads eagerly, silently.
That second condition is the classic “why is my @defer not working”: a viewChild() on the deferred component defeats it entirely.
Triggers:
| Trigger | Fires when |
|---|---|
on idle (default) |
The browser is idle — requestIdleCallback, with an optional timeout |
on viewport |
The placeholder (or a named element) enters the viewport |
on interaction |
The user clicks or presses a key on the placeholder or a named element |
on hover |
The pointer enters the area |
on timer(2s) |
After a duration |
on immediate |
Right after non-deferred content renders |
when <expression> |
A condition becomes true |
Combine with ; for OR semantics, and add a prefetch trigger to download early while showing late:
@defer (on interaction; prefetch on idle) { <settings-panel />} @placeholder { <button>Settings</button>}That is the pattern to reach for by default on interactive panels: the chunk is fetched while the browser is idle, so the panel opens instantly when clicked, and it never competes with the initial load.
The minimum and after parameters exist to stop flicker. @loading (after 100ms; minimum 1s) means “do not show a spinner unless loading takes over 100 ms, and once shown keep it for a second” — which prevents the flash-of-spinner that makes a fast page feel broken. Note that @placeholder, @loading and @error dependencies are all eagerly loaded, so keep them light.
The viewport and interaction triggers watch the placeholder by default, and a placeholder used that way must have a single root element.
Images
Section titled “Images”Images are usually the largest bytes on the page and the LCP element. NgOptimizedImage handles the things everyone forgets:
<img ngSrc="hero.jpg" width="1200" height="600" priority alt="..." /><img ngSrc="thumb.jpg" width="300" height="200" alt="..." />It sets fetchpriority appropriately, lazy-loads non-priority images by default, generates a srcset, adds a preconnect for the image host, and emits a preload hint under SSR. It also enforces practices: width and height are required (preventing layout shift), and it warns when they are wrong or when the image will render distorted.
Mark exactly one image priority — the LCP image. Marking several defeats the purpose, since priority only means anything relative to everything else.
With an image CDN loader configured, srcset generation becomes genuinely valuable: a 400 px-wide thumbnail stops downloading a 2000 px source.
Server-side rendering
Section titled “Server-side rendering”SSR improves first paint and indexability by sending rendered HTML. Hydration then attaches Angular to that existing DOM instead of destroying and rebuilding it — which is the whole point, and why hydration is worth enabling rather than leaving SSR unhydrated. See SSR and Hydration.
Other loading levers
Section titled “Other loading levers”injectAsyncsplits rarely-used services into their own chunks.- Preloading strategies buy back the first-navigation delay that lazy loading introduces — but preloaded chunks consume bandwidth, consume memory, and compete for the browser’s limited connection pool, so aggressive preloading immediately after load can queue behind the images and API calls the user is waiting for. Preload the two or three likely next routes, not everything.
- Barrel files (
index.tsre-exporting a whole feature) are a common cause of a bundler pulling in far more than you imported. Import from the specific file. - Check what your libraries cost. A date-formatting library or an icon set imported wholesale is frequently the largest single item in a bundle, and frequently replaceable with
Intlor a handful of inline SVGs.
Runtime performance
Section titled “Runtime performance”Zoneless is the big one
Section titled “Zoneless is the big one”Under ZoneJS, every DOM event and async task triggers a change-detection pass whether or not state changed. Zoneless removes all of those speculative passes — plus the payload and startup cost of zone.js itself.
Zoneless is the default from v21, so on a current application this is already done. On an older one it is the single largest runtime win available. See Change Detection and Zoneless Angular.
OnPush and signals
Section titled “OnPush and signals”OnPush is the default from v22, and signals notify precisely: writing a signal marks exactly the views that read it. Together they mean the framework does close to the minimum work.
Two practical consequences:
Signals mark whole views, not expressions. A template mixing a per-second ticker with a large static table re-renders the table too. Extracting the ticker into a small child component shrinks the dirty view — a real, measurable optimisation.
computed beats a template method call. {{ formatTotal() }} re-executes on every check of that view; a computed recalculates only when a dependency changed, and only on read.
Slow computations
Section titled “Slow computations”Angular evaluates all template expressions in checked components and runs ngDoCheck, ngOnChanges, ngAfterContentChecked and ngAfterViewChecked sequentially, so one slow computation delays the whole pass. The remedies, in order of preference:
- Fix the algorithm. Speeds up every pass that touches it.
computedsignals — memoised, lazy, dependency-tracked.- Pure pipes — re-evaluated only when inputs change; still the right tool for a transformation applied across many rows.
- Memoisation — more general than a pure pipe, which caches only the most recent result. Watch memory if the argument space is large.
- No layout reads or writes in lifecycle hooks. Reading
offsetHeightorgetBoundingClientRectinngAfterViewCheckedforces synchronous layout on every check.
Zone pollution
Section titled “Zone pollution”On applications still using ZoneJS, third-party libraries that install mousemove handlers or run requestAnimationFrame loops trigger a full pass per tick. Initialise them outside the zone:
this.ngZone.runOutsideAngular(() => this.chart = createChart(el, config));Listeners registered inside also fire outside the zone, so update state through a signal (which notifies regardless) or re-enter with ngZone.run().
Lists are where runtime performance is usually won or lost.
A stable track expression is not optional:
@for (order of orders(); track order.id) { <order-row [order]="order" />}Without a stable identity, Angular cannot match new items to existing DOM nodes and destroys and recreates every row — losing focus, scroll position and component state, and re-running every child’s construction. track $index over a re-sorted or filtered list is effectively no tracking at all.
Virtual scrolling for anything over a few hundred rows. Rendering 10,000 rows costs 10,000 component instances and their subscriptions whatever else you optimise; virtual scrolling renders the visible window. The CDK’s cdk-virtual-scroll-viewport is the standard option.
Paginate on the server where the dataset is genuinely large. No client-side technique beats not sending the data.
Bound live feeds. A signal accumulating an unbounded array from a WebSocket makes every derivation over it progressively slower and eventually exhausts memory. Cap the retained window.
Memory
Section titled “Memory”Memory leaks present as an application that gets slower the longer it is open — often reported as “it’s fine in the morning.”
Sources, roughly by frequency:
- Un-torn-down subscriptions.
takeUntilDestroyed(),toSignal, or theAsyncPipe. effect({ manualCleanup: true })never destroyed.- Global listeners (
window,document) added without removal. - Timers —
setIntervalwithoutclearInterval. - Observers —
IntersectionObserver,ResizeObserver,MutationObservernever disconnected. - A custom
RouteReuseStrategycaching detached route handles. Making Back instant also keeps whole component trees alive with their subscriptions and timers. Destroy the handles you stop using; the router will not. - Root-scoped services accumulating state. A cache with no eviction is a leak with a nicer name.
To find one: DevTools Memory panel, take a heap snapshot, exercise the leaking flow several times, snapshot again, compare and look for detached DOM nodes and component instances that should be gone.
Anti-patterns
Section titled “Anti-patterns”| Anti-pattern | Cost |
|---|---|
| Optimising before profiling | Effort spent where the time is not |
| Method calls in templates | Re-executed on every check of that view |
| Object/array literals in bindings | New reference every check; child never skips |
track $index on a mutable list |
Full re-render; focus and state lost |
| Rendering thousands of rows | Instances, subscriptions and DOM you never see |
Work in ngDoCheck / ngAfterViewChecked |
Multiplied by every pass |
detectChanges() to force an update |
Hides a missing notification; extra work |
| Eager imports of heavy libraries | Bundle bloat, often for a screen most users never open |
| Unoptimised images | Usually the LCP element and the largest download |
| Preloading everything | Competes with critical requests for connections |
@defer with an outside reference |
Silently eager; the block does nothing |
canActivate on a gated lazy route |
Chunk downloads, then access is refused |
A workflow
Section titled “A workflow”- Set budgets in
angular.jsonso regressions fail the build. - Run Lighthouse throttled, in a clean profile. Note LCP, TTFB, INP.
- Analyse the bundle. Anything unexpectedly large is the first target.
- Lazy-load routes at feature boundaries. Use
canMatchfor gated ones. @deferbelow-the-fold and interaction-gated content, withprefetch on idle.- Fix images —
NgOptimizedImage, onepriority, correct dimensions. - Confirm zoneless and check for stray
provideZoneChangeDetection(). - Profile runtime with Angular DevTools while exercising the slow interaction.
- Fix what the profile shows — a slow computation, zone pollution, or an over-large dirty view.
- Check lists — stable
track, virtual scrolling past a few hundred rows. - Re-measure. If the number did not move, revert the change.
Step 11 is the one people skip, and it is the one that keeps the codebase honest.
Trade-offs
Section titled “Trade-offs”| Decision | Favours | Costs |
|---|---|---|
| Lazy routes | Much smaller initial bundle | Delay on first navigation (mitigate with preloading) |
@defer |
Fine-grained deferral inside a page | Placeholder/loading/error states to design; standalone-only |
| Preloading | Instant later navigation | Bandwidth, memory, connection contention |
| SSR + hydration | Faster first paint, indexable | Server infrastructure; server-compatible components |
| Virtual scroll | Constant cost regardless of list size | Fixed or measured heights; Ctrl-F and print break |
computed over methods |
Memoised, lazy | State must be signals |
Custom equal |
Prevents cascades from equal values | Comparison cost on every write |
| Route reuse caching | Instant Back navigation | Memory held; manual handle destruction |
Senior interview scenarios
Section titled “Senior interview scenarios”“An application feels slow. Walk me through your first hour.” Establish which kind of slow before touching anything. Throttled Lighthouse gives LCP and TTFB; if the complaint is “slow to load”, the answer is in the bundle analysis and the network waterfall. If it is “slow to use”, it is the Angular DevTools profiler while reproducing the interaction — many passes on an idle page means zone pollution, one long pass means a slow computation, and the per-component breakdown says which. I would not change a line until one of those numbers has a name attached.
“OnPush everywhere and trackBy on every list, no improvement. What went wrong?”
Those address runtime cost, and the problem was probably loading — an eagerly-imported library, unoptimised images, no route splitting. Or it is runtime but a different cause: a slow computation runs just as slowly under OnPush, and trackBy does nothing if the list is small. It is also worth noting that on current Angular both are defaults or near-defaults, so applying them by hand may have changed nothing at all. The general lesson is that these are the remedies people know rather than the remedies the profile called for.
“Explain @defer, and why it sometimes appears to do nothing.”
@defer splits its contents into a separate chunk loaded on a trigger — viewport, interaction, hover, timer, idle, or a when condition — with @placeholder, @loading and @error sub-blocks. It does nothing when either of two conditions is violated: the dependencies must be standalone, and they must not be referenced anywhere else in the same file, including from a ViewChild query. A viewChild() on the deferred component makes it eager and there is no error to tell you. The pattern I default to for interactive panels is on interaction; prefetch on idle: fetch early, render late.
“When would you not lazy-load a route?” When it is the route most users land on. Splitting the landing route adds a round trip to the critical path for the majority of visits to save bytes for a minority. The same reasoning applies to over-splitting: at some point another chunk costs more in requests, and in connection contention, than it saves in bytes. Route-level splitting at feature boundaries, with preloading for the likely next steps, is the shape that holds up.
“A dashboard gets slower the longer it is open. Where do you look?”
Two candidates. A memory leak — subscriptions not torn down, observers not disconnected, timers not cleared, manualCleanup effects never destroyed, or a RouteReuseStrategy retaining detached handles. Or unbounded growth — a signal accumulating rows from a live feed, so every derivation over it gets slower and every render has more DOM. Heap snapshots before and after exercising the flow will distinguish them: a leak shows detached DOM nodes and component instances that should have been collected; unbounded growth shows one array that keeps getting bigger.
“A list of 5,000 rows scrolls badly. Options?”
First check the track expression — without a stable identity, every update destroys and rebuilds every row, which is usually the whole problem. Then virtual scrolling, so only the visible window exists as components; that turns cost from a function of the dataset into a constant. Then question the requirement: 5,000 rows is rarely something a person reads, so server-side pagination with search and filters is often both faster and a better interface. Simplifying the row component matters too, since its cost is multiplied by whatever number of rows survives.
Related pages
Section titled “Related pages”- Change Detection and Zoneless Angular
- Signals and Angular Reactivity
- Control Flow:
@if,@for,@switch,@defer - Angular Routing in Depth
- SSR and Hydration