Set default value for angular material datePicker with angular 5

ssct79 picture ssct79 · Oct 14, 2018 · Viewed 80.7k times · Source

I'm using a date picker from angular material. I want to set a default value but it is not showing the value.

<mat-form-field class="mr-sm-24" fxFlex (click)="open()" >
   <input matInput [picker]="picker" placeholder="Date"
                  autocomplete="off"
                  name="date" 
                  formControlName="date">
   <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
   <mat-datepicker  [startAt]="startDatePicker" #picker></mat-datepicker>
</mat-form-field>

this is my .js code with the value that i want to set as default

var date = this.datepipe.transform((new Date().getTime()) - 3888000000, 'dd/MM/yyyy'); 

this.form = this.formBuilder.group({
        dataInicial: [data_inicial],
                   ...

Answer

Rohit Parte picture Rohit Parte · Jul 18, 2019

This works for me!

HTML-

<mat-form-field>
    <input matInput [matDatepicker]="picker1" placeholder="From Date" [formControl]="date1">
    <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
    <mat-datepicker  #picker1></mat-datepicker>
</mat-form-field>

TS-

date1 = new FormControl(new Date())