Set default date for datepicker in angular 2 material

Viewed 34161

I'm trying to create datepicker using material.angular.io, but I need to set default date for field. In previose version angular material it was easy. Somebody knows how I can do it now?

my code:

<input mdInput
       name="start_time"
       #start_time="ngModel"
       [mdDatepicker]="startDate"
       [min]="minDate"
       date="true"
       [(ngModel)]="planModel.start_time"
       placeholder="Choose a date">

    <md-datepicker-toggle mdSuffix [for]="startDate"></md-datepicker-toggle>
    <md-datepicker [startView]="dateStart" #startDate></md-datepicker>
3 Answers

You need to initialize your date model. In your ts code, do the following in constructor or in the method where you get planModel:

planModel.start_time = new Date(); // Current Date

Link to working demo.

if you are using reactive forms, below is working angular 10 code:

component.ts

      this.youForm= this._formBuilder.group({


        StartDate: [new Date(), Validators.required],

      });

No change on component.html

  <mat-form-field appearance="outline">
            <input matInput [matDatepicker]="StartDate" placeholder="Start date *" 
              formControlName="StartDate">
            <mat-label>Start Date *</mat-label>
            <mat-datepicker-toggle matSuffix [for]="StartDate"></mat-datepicker-toggle>
            <mat-datepicker #StartDate></mat-datepicker>
          </mat-form-field>

as in reactive form documentation:

xxx.component.html

<mat-form-field>
  <input matInput 
    [matDatepicker]="matDatepicker" 
    [formControl]="dateFormControl"
    (dateChange)="onDateChanged('change', $event)"
    >
  <mat-datepicker-toggle matSuffix [for]="matDatepicker"></mat-datepicker-toggle>
  <mat-datepicker #matDatepicker></mat-datepicker>
</mat-form-field>

xxx.component.ts

currentDate: Date = new Date("12/15/18 00:00:00")
dateFormControl = new FormControl(new Date())

onSomeEvent(){
    this.dateFormControl.setValue(this.currentDate)
}
Related