Skip to content

Commit a62cdb6

Browse files
crisbetojelbourn
authored andcommitted
fix(datepicker): dateInput event being fired if the value hasn't changed (#10952)
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 fbf5648 commit a62cdb6

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-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: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,7 @@ describe('MatDatepicker', () => {
627627

628628
expect(inputEl.classList).toContain('ng-pristine');
629629

630+
inputEl.value = '2001-01-01';
630631
dispatchFakeEvent(inputEl, 'input');
631632
fixture.detectChanges();
632633

@@ -1132,6 +1133,7 @@ describe('MatDatepicker', () => {
11321133
expect(testComponent.onInput).not.toHaveBeenCalled();
11331134
expect(testComponent.onDateInput).not.toHaveBeenCalled();
11341135

1136+
inputEl.value = '2001-01-01';
11351137
dispatchFakeEvent(inputEl, 'input');
11361138
fixture.detectChanges();
11371139

@@ -1179,6 +1181,22 @@ describe('MatDatepicker', () => {
11791181
expect(testComponent.onDateInput).toHaveBeenCalled();
11801182
})
11811183
);
1184+
1185+
it('should not fire the dateInput event if the value has not changed', () => {
1186+
expect(testComponent.onDateInput).not.toHaveBeenCalled();
1187+
1188+
inputEl.value = '12/12/2012';
1189+
dispatchFakeEvent(inputEl, 'input');
1190+
fixture.detectChanges();
1191+
1192+
expect(testComponent.onDateInput).toHaveBeenCalledTimes(1);
1193+
1194+
dispatchFakeEvent(inputEl, 'input');
1195+
fixture.detectChanges();
1196+
1197+
expect(testComponent.onDateInput).toHaveBeenCalledTimes(1);
1198+
});
1199+
11821200
});
11831201

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

0 commit comments

Comments
 (0)