Skip to content

fix(material/datepicker): matDatepickerParse error not being added on first invalid value #11524

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions src/material/datepicker/datepicker-input-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,11 +304,12 @@ export abstract class MatDatepickerInputBase<S, D = ExtractDateTypeFromSelection
let date = this._dateAdapter.parse(value, this._dateFormats.parse.dateInput);
this._lastValueValid = this._isValidValue(date);
date = this._dateAdapter.getValidDateOrNull(date);
const hasChanged = !this._dateAdapter.sameDate(date, this.value);

if (!this._dateAdapter.sameDate(date, this.value)) {
this._assignValue(date);
// We need to fire the CVA change event for all
// nulls, otherwise the validators won't run.
if (!date || hasChanged) {
this._cvaOnChange(date);
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
} else {
// Call the CVA change handler for invalid values
// since this is what marks the control as dirty.
Expand All @@ -320,6 +321,11 @@ export abstract class MatDatepickerInputBase<S, D = ExtractDateTypeFromSelection
this._validatorOnChange();
}
}

if (hasChanged) {
this._assignValue(date);
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
}
}

_onChange() {
Expand Down
12 changes: 12 additions & 0 deletions src/material/datepicker/datepicker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
dispatchFakeEvent,
dispatchKeyboardEvent,
dispatchMouseEvent,
typeInElement,
} from '../../cdk/testing/private';
import {Component, Type, ViewChild, Provider, Directive, ViewEncapsulation} from '@angular/core';
import {ComponentFixture, fakeAsync, flush, inject, TestBed, tick} from '@angular/core/testing';
Expand Down Expand Up @@ -1048,6 +1049,17 @@ describe('MatDatepicker', () => {
subscription.unsubscribe();
}),
);

it('should set the matDatepickerParse error when an invalid value is typed for the first time', () => {
const formControl = fixture.componentInstance.formControl;

expect(formControl.hasError('matDatepickerParse')).toBe(false);

typeInElement(fixture.nativeElement.querySelector('input'), 'Today');
fixture.detectChanges();

expect(formControl.hasError('matDatepickerParse')).toBe(true);
});
});

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