I\'m using a date picker from angular material. I want to set a default value but it is not showing the value.
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())
Here is my answer,
in your .html
<mat-form-field class="mr-sm-24" fxFlex (click)="open()" >
<input [matDatepicker]="picker" matInput placeholder="Date" autocomplete="off" name="date" formControlName="date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
in your .ts
this.form = this.formBuilder.group({
date: new FormControl(new Date()), // Current Date
...
});
This will set current date as default date.
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
in your .html----
<mat-form-field style="width:150px;" color="accent">
<mat-label>Choose From Date</mat-label>
<input class="example-events" matInput [matDatepicker]="picker1" [ngModel]="dateF" >
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1 ></mat-datepicker>
</mat-form-field>
in your .ts----
dateF:any=new Date();
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>))
Below is working code with Angular 10, Angular Material 10 and Reactive forms
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>