There is a already known issue with the mat-datepicker
but the solution is not working perfectly for me because I got different date formats depending on the current selected language of the website.
Angular Material DatePicker Autocomplete
So this is the "solution" that's been given for me. I want the user to be able to also type in the date and not just use the datePicker because why should have an input field which does not work. But yes like the question above said:
Example : if i search an item with 1234 in it and loose focus of the search input, it will complete with 01/01/1234 and do the research with it...
With this solution I can type in everything into the input field. But if I'm entering something wrong the browser console logs:
ERROR Error: InvalidPipeArgument: 'Unable to convert "27.08.1999" into a date' for pipe 'DatePipe'
But the form does not show any error like everything is perfect because it's not validated. Another issue with the solution above is that any selection in the datepicker will end in this format 10/11/2005
but I want to have the german format dd.MM.YYYY
Please notice that my version already contain the changes of the solution above.
StackBlitz: https://stackblitz.com/edit/angular-o5k42x
HTML:
<mat-form-field class="field-sizing">
<input matInput #autocomplete required [max]="globals.currentDate"
placeholder="{{ 'REGISTRATION.DATEOFBIRTH' | translate }}" name="dateOfBirth"
formControlName="dateOfBirth"
[ngClass]="{ 'is-invalid': g.dateOfBirth.touched && g.dateOfBirth.errors }" />
<mat-datepicker-toggle matSuffix [for]="dateOfBirthPicker"></mat-datepicker-toggle>
<mat-datepicker #dateOfBirthPicker startView="multi-year" [startAt]="startDate"></mat-datepicker>
<mat-error class="invalid-feedback"
*ngIf="g.dateOfBirth.touched && g.dateOfBirth.errors && g.dateOfBirth.errors.required">
{{ 'REGISTRATION.DATEOFBIRTH' | translate }} {{ 'VALIDATION.REQUIRED' | translate }}
</mat-error>
</mat-form-field>
<input type="hidden" [matDatepicker]="dateOfBirthPicker"
(dateChange)="autocomplete.value = toFormattedDate($event.value)">
TypeScript:
public personalForm: FormGroup;
get g() {
return this.personalForm.controls;
}
ngOnInit() {
this.buildForm();
}
public buildForm() {
this.personalForm = this.form.group({
dateOfBirth: ['', [Validators.required]],
})
}
toFormattedDate(iso: string) {
const date = new Date(iso);
console.log(date);
return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`;
}
constructor(
public form: FormBuilder
) { }