Angular material Datepicker get value on change

2020-02-28 02:13发布

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);
  }

3条回答
甜甜的少女心
2楼-- · 2020-02-28 02:33

According to the official documentation, the MatDatepickerInput has a dateInput EventEmitter and it's 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>
查看更多
迷人小祖宗
3楼-- · 2020-02-28 02:41
<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

查看更多
beautiful°
4楼-- · 2020-02-28 02:56

Sorry i didn´t post the answer before, but i solved the problem with the comment of @AJT_82. 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 past the $event of the datepicker to get the value.

查看更多
登录 后发表回答