Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value for angular material datePicker with angular 5

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],
                   ...
like image 597
ssct79 Avatar asked Oct 14 '18 04:10

ssct79


People also ask

How do you use material datepicker in angular 6?

mat-datepicker exampleAdd a template reference variable mat-datepicker element. Connect mat-datepicker to input element via [matDatepicker] property. Finally add date picker toggle button to display or hide calender popup by using mat-datepicker-toggle element.


3 Answers

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())
like image 109
Rohit Parte Avatar answered Oct 19 '22 08:10

Rohit Parte


You need to provide a Date object to the startAt change as below:

In .ts:

date = new Date((new Date().getTime() - 3888000000));

In html:

<mat-datepicker  [startAt]="date" #picker></mat-datepicker>

A working demo here: https://stackblitz.com/edit/angular-n9yojx

like image 18
User3250 Avatar answered Oct 19 '22 09:10

User3250


You can use the formControl defined and in your input.

here is html

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

here is TS declare you formControl

date: FormControl;
this.date = new FormControl(new Date(<you can provide you date input field if you getting date from other sources>))
like image 8
Irrfan23 Avatar answered Oct 19 '22 07:10

Irrfan23