Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default date for datepicker in angular 2 material

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>
like image 547
Olga Matosova Avatar asked Sep 20 '17 11:09

Olga Matosova


2 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.

like image 71
Faisal Avatar answered Oct 25 '22 19:10

Faisal


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>
like image 43
MJ X Avatar answered Oct 25 '22 20:10

MJ X