Skip to content

Commit

Permalink
fix(cdk/overlay): run positionChange event inside the zone
Browse files Browse the repository at this point in the history
Fixes that the `positionChange` event of the `CdkConnectedOverlay` directive was running outside the zone.

Fixes #28568.
  • Loading branch information
crisbeto committed Feb 20, 2024
1 parent a2b5fb9 commit eaa5ac7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/cdk/overlay/overlay-directives.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {Component, ElementRef, ViewChild} from '@angular/core';
import {Component, ElementRef, NgZone, ViewChild} from '@angular/core';
import {By} from '@angular/platform-browser';
import {
ComponentFixture,
Expand Down Expand Up @@ -618,6 +618,18 @@ describe('Overlay directives', () => {
.toBe(true);
});

it('should emit the position change handler inside the zone', () => {
let callsInZone: boolean[] = [];

fixture.componentInstance.positionChangeHandler.and.callFake(() => {
callsInZone.push(NgZone.isInAngularZone());
});
fixture.componentInstance.isOpen = true;
fixture.detectChanges();

expect(callsInZone).toEqual([true]);
});

it('should emit when attached', () => {
expect(fixture.componentInstance.attachHandler).not.toHaveBeenCalled();
fixture.componentInstance.isOpen = true;
Expand Down
4 changes: 3 additions & 1 deletion src/cdk/overlay/overlay-directives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
Inject,
InjectionToken,
Input,
NgZone,
OnChanges,
OnDestroy,
Optional,
Expand Down Expand Up @@ -116,6 +117,7 @@ export class CdkConnectedOverlay implements OnDestroy, OnChanges {
private _position: FlexibleConnectedPositionStrategy;
private _scrollStrategyFactory: () => ScrollStrategy;
private _disposeOnNavigation = false;
private _ngZone = inject(NgZone);

/** Origin for the connected overlay. */
@Input('cdkConnectedOverlayOrigin')
Expand Down Expand Up @@ -421,7 +423,7 @@ export class CdkConnectedOverlay implements OnDestroy, OnChanges {
this._positionSubscription = this._position.positionChanges
.pipe(takeWhile(() => this.positionChange.observers.length > 0))
.subscribe(position => {
this.positionChange.emit(position);
this._ngZone.run(() => this.positionChange.emit(position));

if (this.positionChange.observers.length === 0) {
this._positionSubscription.unsubscribe();
Expand Down

0 comments on commit eaa5ac7

Please sign in to comment.