Skip to content

Commit

Permalink
perf(cdk/a11y): avoid triggering change detection if there are no sub…
Browse files Browse the repository at this point in the history
…scribers to stream (angular#15077)

Currently we have an `NgZone.run` call on each `focus` and `blur` event of a monitored
event in order to bring its subscribers into the `NgZone`, however this means that we're
also triggering change detection to any consumers that aren't subscribed to changes
(e.g. `mat-button` only cares about the classes being applied). These changes move
around some logic so that the `NgZone.run` is only hit if somebody has subscribed
to the observable.
  • Loading branch information
crisbeto authored and forsti0506 committed Apr 3, 2022
1 parent d82d809 commit 202496a
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/cdk/a11y/focus-monitor/focus-monitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,11 +436,13 @@ export class FocusMonitor implements OnDestroy {
}

this._setClasses(element);
this._emitOrigin(elementInfo.subject, null);
this._emitOrigin(elementInfo, null);
}

private _emitOrigin(subject: Subject<FocusOrigin>, origin: FocusOrigin) {
this._ngZone.run(() => subject.next(origin));
private _emitOrigin(info: MonitoredElementInfo, origin: FocusOrigin) {
if (info.subject.observers.length) {
this._ngZone.run(() => info.subject.next(origin));
}
}

private _registerGlobalListeners(elementInfo: MonitoredElementInfo) {
Expand Down Expand Up @@ -530,7 +532,7 @@ export class FocusMonitor implements OnDestroy {
elementInfo: MonitoredElementInfo,
) {
this._setClasses(element, origin);
this._emitOrigin(elementInfo.subject, origin);
this._emitOrigin(elementInfo, origin);
this._lastFocusOrigin = origin;
}

Expand Down

0 comments on commit 202496a

Please sign in to comment.