Skip to content

Commit 6fdc237

Browse files
crisbetoandrewseguin
authored andcommitted
fix(overlay): emitting to detachments stream when not attached (#7944)
Currently the `detachments` stream will emit any time the `detach` or `dispose` methods are called, which doesn't reflect actual detachments. It is something I noticed while looking into #7922.
1 parent 0d6d9cc commit 6fdc237

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/cdk/overlay/overlay-ref.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,10 @@ export class OverlayRef implements PortalOutlet {
103103
* @returns The portal detachment result.
104104
*/
105105
detach(): any {
106+
if (!this.hasAttached()) {
107+
return;
108+
}
109+
106110
this.detachBackdrop();
107111

108112
// When the overlay is detached, the pane element should disable pointer events.
@@ -133,6 +137,8 @@ export class OverlayRef implements PortalOutlet {
133137
* Cleans up the overlay from the DOM.
134138
*/
135139
dispose(): void {
140+
const isAttached = this.hasAttached();
141+
136142
if (this._config.positionStrategy) {
137143
this._config.positionStrategy.dispose();
138144
}
@@ -145,7 +151,11 @@ export class OverlayRef implements PortalOutlet {
145151
this._portalOutlet.dispose();
146152
this._attachments.complete();
147153
this._backdropClick.complete();
148-
this._detachments.next();
154+
155+
if (isAttached) {
156+
this._detachments.next();
157+
}
158+
149159
this._detachments.complete();
150160
}
151161

src/cdk/overlay/overlay.spec.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,26 @@ describe('Overlay', () => {
177177
expect(spy).toHaveBeenCalled();
178178
});
179179

180+
it('should not emit to the detach stream if the overlay has not been attached', () => {
181+
let overlayRef = overlay.create();
182+
let spy = jasmine.createSpy('detachments spy');
183+
184+
overlayRef.detachments().subscribe(spy);
185+
overlayRef.detach();
186+
187+
expect(spy).not.toHaveBeenCalled();
188+
});
189+
190+
it('should not emit to the detach stream on dispose if the overlay was not attached', () => {
191+
let overlayRef = overlay.create();
192+
let spy = jasmine.createSpy('detachments spy');
193+
194+
overlayRef.detachments().subscribe(spy);
195+
overlayRef.dispose();
196+
197+
expect(spy).not.toHaveBeenCalled();
198+
});
199+
180200
it('should emit the detachment event after the overlay is removed from the DOM', () => {
181201
let overlayRef = overlay.create();
182202

0 commit comments

Comments
 (0)