UI_Dev
UI_Dev

Reputation: 3417

How to change the date from angular material datepicker?

I have a date-picker from angular material. On click of some event, I'm getting the new date from api service. How do I change the date on some click event?

By Default, I have some date. After click the submit button, there is some api handled(assume), on subscribing the response values there is a variable with date format.

How do I change the date on some click event?

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field> <br/>
<button (click)="dosomeaction()">Submit</button>


export class DatepickerOverviewExample {

   dosomeaction = function(){
     let date = "2018/09/04"; 
     //assign the above date to the input field
   } 
}

stackblitz

Upvotes: 3

Views: 11584

Answers (2)

Nenad Radak
Nenad Radak

Reputation: 3678

You can do it like this

component.html

<mat-form-field>
  <input matInput [matDatepicker]="picker" 
  [(ngModel)]="dateToPass"placeholder="Choose a date">
   <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
   <mat-datepicker #picker></mat-datepicker>
   </mat-form-field> <br/>
  <button (click)="dosomeaction()">Submit</button>

component.ts

  export class DatepickerOverviewExample {

  dateToPass;

 dosomeaction(){
   let date = new Date("2018/09/04");
   //assign the above date to the input field
   this.dateToPass = date;

  }
}

Upvotes: 2

Antoine V
Antoine V

Reputation: 7204

Look at this Stackblitz, just set the date in ngModel

export class DatepickerOverviewExample {
   start_time: Date;
   dosomeaction = function(){
      start_time: new Date();
   } 
}

 <input mdInput
     name="start_time"
     #start_time="ngModel"
     date="true"
     [(ngModel)]="start_time"
     placeholder="Choose a date">

Upvotes: 0

Related Questions