Set default date for datepicker in angular 2 material
31,077
Solution 1
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.
Solution 2
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>
Related videos on Youtube
![Olga Matosova](https://lh3.googleusercontent.com/-3p2NW-gGQJ8/AAAAAAAAAAI/AAAAAAAAACs/1EfdRORTLhM/photo.jpg?sz=256)
Comments
-
Olga Matosova almost 2 years
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>
-
SouthShoreAK almost 5 yearsThis worked for me, but the key wasn't obvious. The value needs to be a
Date
. In our case it was a string, and everything worked, but it would not show on the front end. -
user2026318 about 4 yearsIt sets the value but it doesn't display in the datepicker.
-
user2026318 about 4 yearsActually, you're right...it works. Inside setValue must be a Date(), cannot be string.