Skip to content

Commit 9657ace

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 391a9fd commit 9657ace

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
@@ -324,12 +324,19 @@ export class MatDatepickerInput<D> implements ControlValueAccessor, OnDestroy, V
324324
this._lastValueValid = !date || this._dateAdapter.isValid(date);
325325
date = this._getValidDateOrNull(date);
326326

327-
if (!this._dateAdapter.sameDate(date, this._value)) {
328-
this._value = date;
327+
const hasChanged = !this._dateAdapter.sameDate(date, this._value);
328+
329+
// We need to fire the CVA change event for all
330+
// nulls, otherwise the validators won't run.
331+
if (!date || hasChanged) {
329332
this._cvaOnChange(date);
330-
this._valueChange.emit(date);
331333
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
332334
}
335+
336+
if (hasChanged) {
337+
this._value = date;
338+
this._valueChange.emit(date);
339+
}
333340
}
334341

335342
_onChange() {

src/lib/datepicker/datepicker.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
dispatchFakeEvent,
99
dispatchKeyboardEvent,
1010
dispatchMouseEvent,
11+
typeInElement,
1112
} from '@angular/cdk/testing';
1213
import {Component, FactoryProvider, Type, ValueProvider, ViewChild} from '@angular/core';
1314
import {ComponentFixture, fakeAsync, flush, inject, TestBed, tick} from '@angular/core/testing';
@@ -875,6 +876,19 @@ describe('MatDatepicker', () => {
875876

876877
expect(testComponent.datepickerToggle.disabled).toBe(true);
877878
});
879+
880+
it('should set the matDatepickerParse error when an invalid value is ' +
881+
'typed for the first time', () => {
882+
const formControl = fixture.componentInstance.formControl;
883+
884+
expect(formControl.hasError('matDatepickerParse')).toBe(false);
885+
886+
typeInElement('Today', fixture.nativeElement.querySelector('input'));
887+
fixture.detectChanges();
888+
889+
expect(formControl.hasError('matDatepickerParse')).toBe(true);
890+
});
891+
878892
});
879893

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

0 commit comments

Comments
 (0)