Search code examples
angularangular-materialangular5

Angular Material mat-datepicker (change) event and format


I am using angular material datepicker directive and I have few problems.

1. When I open date picker dialog and select any date, date shows up in input text box, but I want to call a function when ever any change occur in the input text box.

Right now I am triggering function using (input) directive if I manually enter any value in input text box, and this is working fine as shown in code. I want to trigger same function when the date gets changed using the date picker dialog.

2. I also want to change the format of the date from mm/dd/yyyy to dd/mm/yyyy when selected from date picker dialog. Here mm/dd/yyyy is set by default in this directive.

<input matInput [matDatepicker]="organizationValue" formControlName="organizationValue" (input)="orgValueChange(i)">
<mat-datepicker-toggle matSuffix [for]="organizationValue"></mat-datepicker-toggle>                 
<mat-datepicker #organizationValue></mat-datepicker>

Solution

  • from docs you can use one of the below events based on your requirement

    @Output()
    dateChange(): EventEmitter<MatDatepickerInputEvent<D>>
    

    Emits when a change event is fired on this .

    @Output()
    dateInput(): EventEmitter<MatDatepickerInputEvent<D>>
    

    Emits when an input event is fired on this .

    For example:

    <input matInput #ref [matDatepicker]="organizationValue"
        formControlName="organizationValue" (dateChange)="orgValueChange(ref.value)">
    

    or

     <input matInput #ref [matDatepicker]="organizationValue"
         formControlName="organizationValue" (dateInput)="orgValueChange(ref.value)">