I know this is old but it's still a problem with at least Angular 12 and a mat-datepicker. Instead of screwing around with dates, I decided to take a more straightforward approach.
To restate the problem, I'm using a datepicker from Angular Material. When I type in 10/18/2018 in the field and then focus out of it, nothing happens. But if the user types in 2018-10-18, it gets changed around to 10/17/2018. This confuses the user.
Since that is the only input format that seems to be problematic, I use that format and do a simple text transposition.
In my template / .html file:
<input matInput
id="cod-input"
formControlName="commercialOperationDate"
[min]="minDate"
[max]="maxDate"
[matDatepicker]="$any(codPicker)"
(change)="saveDateValue()"
(focusout)="formatDate()">
<mat-datepicker-toggle matSuffix
[for]="codPicker"></mat-datepicker-toggle>
<mat-datepicker #codPicker></mat-datepicker>
In my component / .ts file:
public saveDateValue(): void {
this._codValue = (document.getElementById('cod-input') as HTMLInputElement).value;
}
public formatDate(): void {
const dateValue: string = this._codValue;
if (/^\d{4}-\d{2}-\d{2}$/.exec(dateValue)) {
length = dateValue.length;
const newDateStr =
`${dateValue.substring(length - 5, length - 3)}
/${dateValue.substring(length - 2)}
/${dateValue.substring(0, length - 6)}`;
this.accountLookupForm.get('commercialOperationDate').setValue(new Date(newDateStr))
}
}
To summarize, I save the actual text value of the input field when it is updated by the user. When the user changes focus, I check the text against the problematic regex. And then then I literally just create a new string and set a date based off of the corrected format.
I'm not sure how "professional" this all is, but it sure does work. Even if I hit enter to submit the form while still in the datepicker's input field.