Skip to content

Commit 4c40a5b

Browse files
committed
fix(datepicker): dateInput event being fired if the value hasn't changed
Fixes the `dateInput` event being fired even if the value hasn't changed. This can happen if the browser fires the `input` event while the value hasn't changed (e.g. if the user marks a character and "replaces" it with the same character).
1 parent a0c77e2 commit 4c40a5b

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

src/lib/datepicker/datepicker-input.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -328,10 +328,13 @@ export class MatDatepickerInput<D> implements AfterContentInit, ControlValueAcce
328328
let date = this._dateAdapter.parse(value, this._dateFormats.parse.dateInput);
329329
this._lastValueValid = !date || this._dateAdapter.isValid(date);
330330
date = this._getValidDateOrNull(date);
331-
this._value = date;
332-
this._cvaOnChange(date);
333-
this._valueChange.emit(date);
334-
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
331+
332+
if (!this._dateAdapter.sameDate(date, this._value)) {
333+
this._value = date;
334+
this._cvaOnChange(date);
335+
this._valueChange.emit(date);
336+
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
337+
}
335338
}
336339

337340
_onChange() {

src/lib/datepicker/datepicker.spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1175,6 +1175,22 @@ describe('MatDatepicker', () => {
11751175
expect(testComponent.onDateInput).toHaveBeenCalled();
11761176
})
11771177
);
1178+
1179+
it('should not fire the dateInput event if the value has not changed', () => {
1180+
expect(testComponent.onDateInput).not.toHaveBeenCalled();
1181+
1182+
inputEl.value = '12/12/2012';
1183+
dispatchFakeEvent(inputEl, 'input');
1184+
fixture.detectChanges();
1185+
1186+
expect(testComponent.onDateInput).toHaveBeenCalledTimes(1);
1187+
1188+
dispatchFakeEvent(inputEl, 'input');
1189+
fixture.detectChanges();
1190+
1191+
expect(testComponent.onDateInput).toHaveBeenCalledTimes(1);
1192+
});
1193+
11781194
});
11791195

11801196
describe('with ISO 8601 strings as input', () => {

0 commit comments

Comments
 (0)