In this post i will show you how to use angular material datepicker and you can easily implement angular material datepicker in your angular project. Datepicker is very common in every project mostly used in registration form to enter DOB.
Let's see how we can implement the angular material datepicker.
STEP 1 - Create new angular project
If @angular/cli is not installed in your system then first install angular/cli .Open the command prompt or terminal and run the below command to install @angular/cli
npm install -g @angular/cli
Open the command prompt or terminal and run the below command , this command will create new angular project
ng new DatepickerApp
STEP 2 - Install the Angular Material Package
Open the DatepickerApp and install the Angular Material package by running below command
ng add @angular/material
STEP 3 - Install the Angular Material Package
Import few material modules in the app.module file
- MatDatepickerModule
- MatNativeDateModule
- MatFormFieldModule
- MatInputModule
src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {MatDatepickerModule} from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatDatepickerModule,
MatNativeDateModule,
MatFormFieldModule,
MatInputModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
STEP 4 - Add the datepicker in the view
Now we are almost done , in this last step we are going to add the datepicker code in the html view , in this example i have used app.component.html
but you can use any component html file.
src/app/app.component.html
<form action="" style="margin: auto; width: 50%;">
<h2>Code Learning Point Datepicker Example</h2>
<mat-form-field>
<input matInput [matDatepicker]="picker" placeholder="Choose a date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</form>
Now you are ready just run the local server , run the below command to start the server
ng serve
Open this URL http://localhost:4200/