Skip to content

Commit 75ad13e

Browse files
committed
fix(datepicker): matDatepickerParse error not being added on first invalid value
Fixes the datepicker not adding the `matDatepickerParse` error if the user enters an invalid string as their first value. The issue comes from the fact that we don't call the function from the `ControlValueAccessor` if the value hasn't changed, which means that the validator won't be re-run. Fixes #11523.
1 parent 9062640 commit 75ad13e

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

src/lib/datepicker/datepicker-input.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -329,12 +329,19 @@ export class MatDatepickerInput<D> implements AfterContentInit, ControlValueAcce
329329
this._lastValueValid = !date || this._dateAdapter.isValid(date);
330330
date = this._getValidDateOrNull(date);
331331

332-
if (!this._dateAdapter.sameDate(date, this._value)) {
333-
this._value = date;
332+
const hasChanged = !this._dateAdapter.sameDate(date, this._value);
333+
334+
// We need to fire the CVA change event for all
335+
// nulls, otherwise the validators won't run.
336+
if (!date || hasChanged) {
334337
this._cvaOnChange(date);
335-
this._valueChange.emit(date);
336338
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
337339
}
340+
341+
if (hasChanged) {
342+
this._value = date;
343+
this._valueChange.emit(date);
344+
}
338345
}
339346

340347
_onChange() {

src/lib/datepicker/datepicker.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
dispatchFakeEvent,
77
dispatchKeyboardEvent,
88
dispatchMouseEvent,
9+
typeInElement,
910
} from '@angular/cdk/testing';
1011
import {Component, FactoryProvider, Type, ValueProvider, ViewChild} from '@angular/core';
1112
import {ComponentFixture, fakeAsync, flush, inject, TestBed} from '@angular/core/testing';
@@ -781,6 +782,19 @@ describe('MatDatepicker', () => {
781782

782783
expect(testComponent.datepickerToggle.disabled).toBe(true);
783784
});
785+
786+
it('should set the matDatepickerParse error when an invalid value is ' +
787+
'typed for the first time', () => {
788+
const formControl = fixture.componentInstance.formControl;
789+
790+
expect(formControl.hasError('matDatepickerParse')).toBe(false);
791+
792+
typeInElement('Today', fixture.nativeElement.querySelector('input'));
793+
fixture.detectChanges();
794+
795+
expect(formControl.hasError('matDatepickerParse')).toBe(true);
796+
});
797+
784798
});
785799

786800
describe('datepicker with mat-datepicker-toggle', () => {

0 commit comments

Comments
 (0)