Search code examples
angulartypescriptangular-materialdatepicker

How to define an optional setting value in the datepicker using Material?


I am trying to create a reusable component of the Material datepicker but I can't find a solution to have a optional setting date of the component.

resusable.datepicker.component.ts

@Input() currentValue: FormControl = new FormControl<any>(new Date());

resusable.datepicker.component.html

<mat-form-field appearance="fill">
  <input
    name="{{ name }}"
    matInput
    [matDatepicker]="picker"
    [value]="currentValue.value"
  />
  <mat-datepicker-toggle matSuffix [for]="picker">
  </mat-datepicker-toggle>
  <mat-datepicker touchUi #picker></mat-datepicker>
</mat-form-field>

usage.component.html

<app-ftd-date-picker
  [currentValue]="selectedDate"
></app-ftd-date-picker>
<app-ftd-date-picker
></app-ftd-date-picker>

usage.component.ts

export class AppComponent {
  selectedDate = new FormControl(new Date(2025, 11, 25));
}

The problem is that when i use the component without setting the default date, it needs to have this changed: resusable.datepicker.component.ts

@Input() currentValue: FormControl = new FormControl<any> | undefined;

But i am unable to find a solution. Any suggestions? Thank you.


Solution

  • The solution was clear after a night sleep... just change this line:

    resusable.datepicker.component.ts

    @Input() currentValue: FormControl = new FormControl();
    

    This way the typing is correct and the default is a non date.