Skip to content

Commit 7be61b6

Browse files
crisbetoandrewseguin
authored andcommitted
fix(material/slider): avoid error on some touchstart events (#23823)
Fixes that the slider was throwing errors on some non-cancelable `touchstart` events. Fixes #23820. (cherry picked from commit 78db0d4)
1 parent 81528bc commit 7be61b6

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/material/slider/slider.spec.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ import {
1818
dispatchKeyboardEvent,
1919
dispatchMouseEvent,
2020
createKeyboardEvent,
21-
} from '../../cdk/testing/private';
21+
createTouchEvent,
22+
} from '@angular/cdk/testing/private';
2223
import {Component, DebugElement, Type, ViewChild} from '@angular/core';
2324
import {ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing';
2425
import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms';
@@ -242,6 +243,17 @@ describe('MatSlider', () => {
242243
it('should have a focus indicator', () => {
243244
expect(sliderNativeElement.classList.contains('mat-focus-indicator')).toBe(true);
244245
});
246+
247+
it('should not try to preventDefault on a non-cancelable event', () => {
248+
const event = createTouchEvent('touchstart');
249+
const spy = spyOn(event, 'preventDefault');
250+
Object.defineProperty(event, 'cancelable', {value: false});
251+
252+
dispatchEvent(sliderNativeElement, event);
253+
fixture.detectChanges();
254+
255+
expect(spy).not.toHaveBeenCalled();
256+
});
245257
});
246258

247259
describe('disabled slider', () => {

src/material/slider/slider.ts

+7-1
Original file line numberDiff line numberDiff line change
@@ -672,14 +672,20 @@ export class MatSlider
672672
const oldValue = this.value;
673673
this._isSliding = 'pointer';
674674
this._lastPointerEvent = event;
675-
event.preventDefault();
676675
this._focusHostElement();
677676
this._onMouseenter(); // Simulate mouseenter in case this is a mobile device.
678677
this._bindGlobalEvents(event);
679678
this._focusHostElement();
680679
this._updateValueFromPosition(pointerPosition);
681680
this._valueOnSlideStart = oldValue;
682681

682+
// Despite the fact that we explicitly bind active events, in some cases the browser
683+
// still dispatches non-cancelable events which cause this call to throw an error.
684+
// There doesn't appear to be a good way of avoiding them. See #23820.
685+
if (event.cancelable) {
686+
event.preventDefault();
687+
}
688+
683689
// Emit a change and input event if the value changed.
684690
if (oldValue != this.value) {
685691
this._emitInputEvent();

0 commit comments

Comments
 (0)