Angular Material Datepicker : Set Value

By Arvind Rai, July 10, 2020
This page will walk through Angular Material Datepicker set value example. The Datepicker with MatNativeDateModule, uses native JavaScript Date API. The Datepicker with MatMomentDateModule, uses moment.js API.
Here on this page we will provide code to set date to Datepicker with native Date and moment using reactive form.

Technologies Used

Find the technologies being used in our example.
1. Angular 10.0.0
2. Angular Material 10.0.0
3. Node.js 12.5.0
4. NPM 6.9.0
5. moment.js 2.27.0

Set Date with Moment

When we create our Datepicker using MatMomentDateModule then to set the date, we need to use moment.
Import the moment.
import * as _moment from 'moment';
const moment = _moment; 

Suppose we have a FormControl. We can pass moment as following.
releaseDate = new FormControl(moment("10-20-2020", "MM-DD-YYYY")); 
Find the code to bind releaseDate with Datepicker.
<mat-form-field>
  <mat-label>Release Date</mat-label>
  <input matInput [matDatepicker]="relDob" [formControl]="releaseDate">
  <mat-datepicker-toggle matSuffix [for]="relDob"></mat-datepicker-toggle>
  <mat-datepicker #relDob></mat-datepicker>
</mat-form-field> 
Find one more example to set date. Here we have a FormGroup.
setDefaultDate() {
 this.studentForm.patchValue({
   dateOfBirth: moment("12/25/1995", "MM/DD/YYYY"),
   admDateRange: {
	 startDate: moment("June 01, 2020", "MMM DD,YYYY"),
	 endDate: moment("July 31, 2020", "MMM DD,YYYY")
   }
 });
} 
Call setDefaultDate() inside ngOnInit() or button click or using other events to set default date.
We can set moment in following ways.
1.
moment() 
Sets the current date and time from system.
2.
moment("10-25-1995", "MM-DD-YYYY") 
The given date string is parsed according to given date format.
3.
moment("2018-10-25 6:30 +0000", "YYYY-MM-DD HH:mm Z") 
Date and time string is parsed according to given date time format and time zone.
4.
moment([2018, 5, 14, 15, 25, 50, 525]) 
The moment can be instantiated using array with given format.
[year, month, day, hour, minute, second, millisecond] 
Except the year, other values are optional. We can assign moment as following, too.
moment([2018, 5, 20]) 

Set Date with Native JavaScript Date

To create Datepicker with native JavaScript Date we need to import MatNativeDateModule in our application module.
To set date with native JavaScript Date, we can pass the Date to our FormControl.
releaseDate = new FormControl(new Date(2020, 9, 20)); 
Find the code to use native Date with FormGroup.
setDefaultDate() {
 this.studentForm.patchValue({
   dateOfBirth: new Date(1995, 11, 25),
   admDateRange: {
	 startDate: new Date(2020, 5, 1),
	 endDate: new Date(2020, 6, 31)
   }
 });
} 

Complete Example

Find the complete code of our demo application to set value to Datepicker using moment.js.
student.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl } from '@angular/forms';
import { StudentService } from './student.service';

import * as _moment from 'moment';
import { Moment } from 'moment';

const moment = _moment;

@Component({
  selector: 'app-student',
  templateUrl: './student.component.html'
})
export class StudentComponent implements OnInit {
  constructor(private formBuilder: FormBuilder, private studentService: StudentService) { }
  ngOnInit() {
  }
  studentForm = this.formBuilder.group({
    name: '',
    dateOfBirth: '',
    admDateRange: this.formBuilder.group({
      startDate: '',
      endDate: ''
    })
  });
  onFormSubmit() {
    this.studentService.saveStudent(this.studentForm.value);
    let dateOfBirth: Moment = this.studentForm.get('dateOfBirth').value;
    console.log(dateOfBirth.toObject());
    let yearOfBirth = dateOfBirth.toObject().years;
    console.log('yearOfBirth : ', yearOfBirth);
    this.studentForm.reset();
  }
  setDefaultDate() {
    this.studentForm.patchValue({
      dateOfBirth: moment("12/25/1995", "MM/DD/YYYY"),
      admDateRange: {
        startDate: moment("June 01, 2020", "MMM DD,YYYY"),
        endDate: moment("July 31, 2020", "MMM DD,YYYY")
      }
    });
  }
} 
student.component.html
<h3>Datepicker Set Value</h3>
<form [formGroup]="studentForm" (ngSubmit)="onFormSubmit()">
  <mat-form-field>
    <mat-label>Student Name</mat-label>
    <input matInput formControlName="name">
  </mat-form-field>
  <br/>
  <mat-form-field appearance="fill">
    <mat-label>Date of Birth</mat-label>
    <input matInput [matDatepicker]="dob" formControlName="dateOfBirth">
    <mat-datepicker-toggle matSuffix [for]="dob"></mat-datepicker-toggle>
    <mat-datepicker #dob></mat-datepicker>
  </mat-form-field>
  <br/>
  <mat-form-field appearance="fill">
    <mat-label>Admission Date Range</mat-label>
    <mat-date-range-input [rangePicker]="admDateRangePicker"  formGroupName="admDateRange">
      <input matStartDate formControlName="startDate" placeholder="Start date">
      <input matEndDate formControlName="endDate" placeholder="End date">
    </mat-date-range-input>
    <mat-datepicker-toggle matSuffix [for]="admDateRangePicker"></mat-datepicker-toggle>
    <mat-date-range-picker #admDateRangePicker></mat-date-range-picker>
  </mat-form-field>
  <br/><br/>
  <button mat-raised-button>Submit</button>
  <button mat-raised-button type="button" (click)="setDefaultDate()">Set Default Dates</button>
</form> 
student.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class StudentService {
  saveStudent(student) {
    console.log(JSON.stringify(student));
  }
} 
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
      <app-student></app-student>
  `
})
export class AppComponent {
} 
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule }    from '@angular/forms'; 
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatInputModule } from '@angular/material/input';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatMomentDateModule } from '@angular/material-moment-adapter';

import { AppComponent } from './app.component';
import { StudentComponent } from './student.component';

@NgModule({
  declarations: [
    AppComponent,
    StudentComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,
    MatInputModule, 
    MatDatepickerModule,
    MatMomentDateModule
  ],
  providers: [
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { } 

Run Application

To run the application, find the steps.
1. Install Angular CLI using link.
2. Install Angular Material using link.
3. Download source code using download link given below on this page.
4. Use downloaded src in your Angular CLI application.
5. Run ng serve using command prompt.
6. Access the URL http://localhost:4200
Find the print screen of the output after clicking Set Default Dates button.
Angular Material Datepicker : Set Value

References

Datepicker
Moment.js Documentation

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us