Skip to content

Commit 8d79cc8

Browse files
crisbetoandrewseguin
authored andcommitted
fix(global-position-strategy): error if disposed before applied (#8761)
Fixes an error that is thrown by the `GlobalPositionStrategy` if its connected `OverlayRef` is disposed before the strategy is applied. This could happen, because the `OverlayRef` applies the position strategy asynchronously. Fixes #8758.
1 parent 3066929 commit 8d79cc8

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

src/cdk/overlay/position/global-position-strategy.spec.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {OverlayModule, Overlay, OverlayRef, GlobalPositionStrategy} from '../ind
55
describe('GlobalPositonStrategy', () => {
66
let element: HTMLElement;
77
let strategy: GlobalPositionStrategy;
8+
let hasOverlayAttached: boolean;
89

910
beforeEach(() => {
1011
TestBed.configureTestingModule({imports: [OverlayModule]});
@@ -15,11 +16,18 @@ describe('GlobalPositonStrategy', () => {
1516

1617
element = document.createElement('div');
1718
document.body.appendChild(element);
18-
strategy.attach({overlayElement: element} as OverlayRef);
19+
hasOverlayAttached = true;
20+
strategy.attach({
21+
overlayElement: element,
22+
hasAttached: () => hasOverlayAttached
23+
} as OverlayRef);
1924
});
2025

2126
afterEach(() => {
22-
element.parentNode!.removeChild(element);
27+
if (element.parentNode) {
28+
element.parentNode.removeChild(element);
29+
}
30+
2331
strategy.dispose();
2432
});
2533

@@ -151,4 +159,12 @@ describe('GlobalPositonStrategy', () => {
151159
expect(element.style.marginTop).toBe('0px');
152160
expect((element.parentNode as HTMLElement).style.alignItems).toBe('flex-start');
153161
});
162+
163+
it('should not throw when attempting to apply after the overlay has been disposed', () => {
164+
strategy.dispose();
165+
element.parentNode!.removeChild(element);
166+
hasOverlayAttached = false;
167+
168+
expect(() => strategy.apply()).not.toThrow();
169+
});
154170
});

src/cdk/overlay/position/global-position-strategy.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,13 @@ export class GlobalPositionStrategy implements PositionStrategy {
146146
* @returns Resolved when the styles have been applied.
147147
*/
148148
apply(): void {
149+
// Since the overlay ref applies the strategy asynchronously, it could
150+
// have been disposed before it ends up being applied. If that is the
151+
// case, we shouldn't do anything.
152+
if (!this._overlayRef.hasAttached()) {
153+
return;
154+
}
155+
149156
const element = this._overlayRef.overlayElement;
150157

151158
if (!this._wrapper && element.parentNode) {

0 commit comments

Comments
 (0)