Angular material Datepicker get value on change

84,014

Solution 1

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.

Solution 2

<mat-form-field>
  <input matInput [matDatepicker]="expiration1" placeholder="Expiration" [formControl]="expiration" required (dateChange)="EndDateChange($event)">
  <mat-datepicker-toggle matSuffix [for]="expiration1"></mat-datepicker-toggle>
  <mat-datepicker #expiration1></mat-datepicker>
</mat-form-field>

Please check this demo link So you will get more idea. Example

Solution 3

According to the official documentation, the MatDatepickerInput has a dateInput EventEmitter and it emits the selected date.

<mat-form-field>
 <input (dateInput)="OnDateChange($event.value)" matInput [matDatepicker]="picker" 
 [placeholder]="field.label" />
 <mat-datepicker-toggle matSuffix [for]="picker"> </mat-datepicker-toggle>
 <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
Share:
84,014
Miguel Frias
Author by

Miguel Frias

Updated on May 03, 2021

Comments

  • Miguel Frias
    Miguel Frias about 3 years

    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);
      }
    
  • rainversion_3
    rainversion_3 over 4 years
    selectedChanged seems to be removed in later versions of mat-datepicker
  • Jonath P
    Jonath P over 3 years
    input tag not closed?
  • Géza
    Géza about 2 years
    Is there a solution for that?
  • Morato_dev
    Morato_dev about 2 years
    It's closed on the line below, the "[placeholder]="field.label" " belongs to it
  • De Bonheur
    De Bonheur about 2 years
    @JonathP it's closed by the line juste below