Skip to content

Commit

Permalink
fix(material/slider): error if slider is destroyed before first chang…
Browse files Browse the repository at this point in the history
…e 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)
  • Loading branch information
crisbeto committed Jan 29, 2024
1 parent 251293f commit 9e02a11
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/material/slider/slider-thumb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export class MatSliderVisualThumb implements _MatSliderVisualThumb, AfterViewIni
private _sliderInput: _MatSliderThumb;

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

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

ngOnDestroy() {
const input = this._sliderInputEl;
input.removeEventListener('pointermove', this._onPointerMove);
input.removeEventListener('pointerdown', this._onDragStart);
input.removeEventListener('pointerup', this._onDragEnd);
input.removeEventListener('pointerleave', this._onMouseLeave);
input.removeEventListener('focus', this._onFocus);
input.removeEventListener('blur', this._onBlur);

if (input) {
input.removeEventListener('pointermove', this._onPointerMove);
input.removeEventListener('pointerdown', this._onDragStart);
input.removeEventListener('pointerup', this._onDragEnd);
input.removeEventListener('pointerleave', this._onMouseLeave);
input.removeEventListener('focus', this._onFocus);
input.removeEventListener('blur', this._onBlur);
}
}

private _onPointerMove = (event: PointerEvent): void => {
Expand Down
10 changes: 10 additions & 0 deletions src/material/slider/slider.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,16 @@ describe('MDC-based MatSlider', () => {
}
}

// Note that this test is outside of the other `describe` blocks, because they all run
// `detectChanges` in the `beforeEach` and we're testing specifically what happens if it
// is destroyed before change detection has run.
it('should not throw if a slider is destroyed before the first change detection run', () => {
expect(() => {
const fixture = createComponent(StandardSlider);
fixture.destroy();
}).not.toThrow();
});

describe('standard slider', () => {
let fixture: ComponentFixture<StandardSlider>;
let slider: MatSlider;
Expand Down

0 comments on commit 9e02a11

Please sign in to comment.