Angular material Datepicker get value on change

Issue

I’m using the new version of angular and angular material. I need to get the value of the datepicker at the moment the user change the date to then pass that value to a function and do something.

datepicker

  <mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Choose a date" [(ngModel)]="roomsFilter.date">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker [(ngModel)]="roomsFilter.date" ngDefaultControl (selectedChanged)="onChange($event)"></mat-datepicker>
  </mat-form-field>

and this the function.

  public onChange(event: any, newDate: any): void {
    console.log(event.target.value);
    // this.getData(newDate);
  }

Solution

Sorry I didn’t post the answer before, but I solved the problem with the @AJT_82’s comment. Here is the code:

Component HTML

  <mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Choose a date" [(ngModel)]="roomsFilter.date">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker [(ngModel)]="roomsFilter.date" ngDefaultControl (selectedChanged)="onDate($event)"></mat-datepicker>
  </mat-form-field>

compoment ts

  public onDate(event): void {
    this.roomsFilter.date = event;
    this.getData(this.roomsFilter.date);
  }

Basically, I just passed the $event of the datepicker to get the value.

Answered By – Miguel Frias

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.