Skip to content

Commit 9e02a11

Browse files
committed
fix(material/slider): error if slider is destroyed before first change detection (#28494)
Fixes that the slider was throwing an error if it's destroyed before `ngAfterViewInit` has run. Fixes #28475. (cherry picked from commit 4176633)
1 parent 251293f commit 9e02a11

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

src/material/slider/slider-thumb.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ export class MatSliderVisualThumb implements _MatSliderVisualThumb, AfterViewIni
7575
private _sliderInput: _MatSliderThumb;
7676

7777
/** The native html element of the slider input corresponding to this thumb. */
78-
private _sliderInputEl: HTMLInputElement;
78+
private _sliderInputEl: HTMLInputElement | undefined;
7979

8080
/** The RippleRef for the slider thumbs hover state. */
8181
private _hoverRippleRef: RippleRef | undefined;
@@ -129,12 +129,15 @@ export class MatSliderVisualThumb implements _MatSliderVisualThumb, AfterViewIni
129129

130130
ngOnDestroy() {
131131
const input = this._sliderInputEl;
132-
input.removeEventListener('pointermove', this._onPointerMove);
133-
input.removeEventListener('pointerdown', this._onDragStart);
134-
input.removeEventListener('pointerup', this._onDragEnd);
135-
input.removeEventListener('pointerleave', this._onMouseLeave);
136-
input.removeEventListener('focus', this._onFocus);
137-
input.removeEventListener('blur', this._onBlur);
132+
133+
if (input) {
134+
input.removeEventListener('pointermove', this._onPointerMove);
135+
input.removeEventListener('pointerdown', this._onDragStart);
136+
input.removeEventListener('pointerup', this._onDragEnd);
137+
input.removeEventListener('pointerleave', this._onMouseLeave);
138+
input.removeEventListener('focus', this._onFocus);
139+
input.removeEventListener('blur', this._onBlur);
140+
}
138141
}
139142

140143
private _onPointerMove = (event: PointerEvent): void => {

src/material/slider/slider.spec.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,16 @@ describe('MDC-based MatSlider', () => {
9191
}
9292
}
9393

94+
// Note that this test is outside of the other `describe` blocks, because they all run
95+
// `detectChanges` in the `beforeEach` and we're testing specifically what happens if it
96+
// is destroyed before change detection has run.
97+
it('should not throw if a slider is destroyed before the first change detection run', () => {
98+
expect(() => {
99+
const fixture = createComponent(StandardSlider);
100+
fixture.destroy();
101+
}).not.toThrow();
102+
});
103+
94104
describe('standard slider', () => {
95105
let fixture: ComponentFixture<StandardSlider>;
96106
let slider: MatSlider;

0 commit comments

Comments
 (0)