Sub topic 14
Checking third-party library compatibility
You can make your own components zoneless-ready, but your app also runs code you did not write: UI kits, chart libraries, state libraries, and SDKs. This chapter shows how to find out whether a dependency works without Zone.js, how to test it, and what to do when it doesn't.
This chapter assumes you know how zoneless change detection is scheduled (signals, markForCheck(), the async pipe, event listeners in templates). It also assumes you have enabled provideZonelessChangeDetection() and written TestBed tests with fixture.whenStable().
Why libraries break
A library is zoneless-compatible when every state change that affects its view reaches Angular through a channel Angular listens to. Zone.js used to hide gaps in that rule. A library could change a field inside a setTimeout, a WebSocket callback, or a raw addEventListener handler, and Zone.js would still trigger a check afterwards. Without Zone.js, that same change is silent.
Libraries fail in three main ways:
- Silent staleness. The library mutates plain fields from an async callback, and the view never updates. No error appears.
- Missing global. The library references
Zone, for exampleZone.currentorZone.root. Oncezone.jsis removed, this throwsReferenceError: Zone is not defined. - Zone-event dependence. The library subscribes to
NgZone.onStableorNgZone.onMicrotaskEmptyto run code after rendering. In a zoneless app those events do not fire as they did, so the code never runs.
The first failure is the hardest to catch because the app compiles and starts normally.
Compatibility signals to look for
Start with cheap checks before you write any tests.
- Documentation and changelog. Search the library's docs and release notes for "zoneless", "signals", or "OnPush". Angular Material and the CDK are the reference case: the Angular team maintains them and tests them zoneless.
- Peer dependencies. A
zone.jsentry inpeerDependenciessuggests the library expects Zone.js. It does not prove the library breaks, but it is worth reading. - Component style. Components declared with
ChangeDetectionStrategy.OnPushthat expose signal inputs andoutput()are usually safe. Libraries built on RxJS observables consumed through the async pipe are also usually safe. - Source search. Search the installed package for zone-specific APIs.
# Run from your project root. Replace some-lib with the package name.
grep -rnE "onMicrotaskEmpty|onStable|Zone\.current|Zone\.root|isInAngularZone" \
node_modules/some-lib --include="*.mjs" --include="*.js"Each hit needs a look. A call to ngZone.run(() => ...) is harmless without zones, because it just calls the function. A call to ngZone.runOutsideAngular(...) is also harmless. A subscription to onStable that drives rendering logic is a problem. So is any use of the Zone global.
Testing a library in your own app
Search results do not replace a real run. The safest procedure keeps Zone.js installed at first, so a failure points to change detection and not to a missing global.
- Add
provideZonelessChangeDetection()to your providers but leavezone.jsinpolyfills. - Exercise every screen that uses the library: change inputs, trigger its callbacks, wait for its timers.
- Remove
zone.jsfrom the build and test polyfills and repeat. Failures now include the missing-global kind.
Automate the library-specific part in a test. This one renders a component that wraps the library, changes state through the library's own API, and waits for stability.
import { TestBed } from '@angular/core/testing';
import { provideZonelessChangeDetection } from '@angular/core';
import { ProductChart } from './product-chart';
describe('ProductChart with a third-party library', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideZonelessChangeDetection()],
});
});
it('shows updated data after the library finishes its async work', async () => {
const fixture = TestBed.createComponent(ProductChart);
await fixture.whenStable();
fixture.componentRef.setInput('series', [3, 5, 8]);
await fixture.whenStable();
expect(fixture.nativeElement.textContent).toContain('Total: 16');
});
});If the library completes work after a timer or network call and the assertion fails only in zoneless mode, the library changes state without notifying Angular. Note that whenStable() only waits for work Angular knows about. A library that uses raw timers is invisible to it, so you may need to wait explicitly in the test, for example with fakeAsync and tick(), or by polling for the expected DOM.
Bridging an incompatible library
When a library fails and you cannot replace it, put a thin adapter between it and your templates. The adapter turns the library's notifications into something Angular listens to. This is usually better than editing the library or calling markForCheck() in many places.
Suppose a widget dispatches a DOM CustomEvent called selection-change when the user picks an item, and the old code stored the result in a plain field. Convert the event stream into a signal:
import { ChangeDetectionStrategy, Component, ElementRef, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { fromEvent, map } from 'rxjs';
@Component({
selector: 'app-picker',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="widget"></div>
<p>Selected: {{ selected() }}</p>
`,
})
export class Picker {
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;
protected readonly selected = toSignal(
fromEvent<CustomEvent<string>>(this.host, 'selection-change').pipe(
map((event) => event.detail),
),
{ initialValue: 'nothing' },
);
}toSignal() subscribes in the injection context and unsubscribes when the component is destroyed. Because selected is a signal read in the template, each event marks the view for refresh without Zone.js.
For callback-style APIs without events, wrap the callback with signal.set() or call ChangeDetectorRef.markForCheck() inside it. Keep that code in one adapter component or service, so the workaround lives in one place and can be deleted when the library is fixed.
Symptom guide
| Symptom | Likely cause | Fix |
|---|---|---|
| View updates only after you click elsewhere | Library mutates fields in a timer or raw listener | Bridge with a signal, `toSignal()`, or `markForCheck()` |
| `ReferenceError: Zone is not defined` | Library reads the `Zone` global | Upgrade the library, replace it, or keep `zone.js` loaded |
| Code that should run after render never runs | Library waits on `onStable` or `onMicrotaskEmpty` | Use `afterNextRender()` in your wrapper, or upgrade |
| Test passes locally but asserts too early | Library work is not tracked as a pending task | Wrap your calls in `PendingTasks.run()` or wait explicitly in the test |
| Works zoneless, but SSR output is empty | Async library work is untracked, so the server serializes early | Track the work with `PendingTasks` in your wrapper |
Deciding what to do with an incompatible library
Weigh these options in order:
- Upgrade. A newer major version may already support zoneless mode. Check release notes before anything else.
- Wrap. If the library is small or isolated, an adapter as shown above costs little.
- Replace. If the library is unmaintained and used widely in your templates, replacing it may cost less than maintaining wrappers.
- Defer zoneless. Keep
zone.jsand stay on zone-based detection for now. Component-level OnPush and signal work still pays off, and you can switch later.
Record the decision for each library in your migration notes, with the version you tested, so a later upgrade can be rechecked quickly.
Exercise
Your app uses a chart library. After you enable provideZonelessChangeDetection() (with zone.js still loaded), the chart's legend keeps showing old values after a data refresh that arrives through a setTimeout inside the library. Name two ways to confirm that the library is the cause, and one way to fix the display without editing the library.
Show answer
To confirm: (1) call markForCheck() or trigger an unrelated event such as a click and see whether the legend then updates, which shows the library changed state without notifying Angular; (2) write a TestBed test with zoneless enabled that changes the data, awaits fixture.whenStable(), and asserts the legend text, then compare it with the same test under zone-based detection. To fix it: wrap the chart in an adapter component that listens to the library's update callback or event and writes the result to a signal (for example with signal.set() or toSignal()), and read that signal in the template.