Let’s pick a date with ng2-datepicker

F.Laurens
F.Laurens
Jul 27, 2017 · 2 min read

It is not so easy to create a good date picker from scratch . That is why we are always so happy to find a component or plugin that does it for us in our Angular project! ng2-datepicker is an npmjs component I am testing here to quickly display a nice date picker!

Sponsored by letsboot.com

What we will do:

  • install the ng2-datepicker in your Angular project
  • implement it into the app component
  • edit the template to display the calendar

Check out our Angular in-house trainings or a public Angular courses.
Try out fossilo.com, our angular project to archive complete websites.

Go to our Letsboot Youtube channel

Install ng2-datepicker

In your Angular project repository, run the following command line to install ng2-datepicker:

npm install ng2-datepicker --save

Then, in your app module, import DatePickerModule (line 6) and add it in the imports of NgModule (line 15):

Implement the date picker in the component

In your app component, import DatePickerOptions and DateModel and set up 2 properties: date and options. Date is set to DateModel (line 13). Options is set to DatePickerOptions (line 14) where you can set all calendar options you want:

You can get more options such as minDate, maxDate, format… in the official documentation on Github.

Edit the app template

In your app template, add the ng2-datepicker tag. Set the options to your date picker options and ngModel to date (defined in the app.component.ts) as follows:

<ng2-datepicker [options]="options" [(ngModel)]="date">
</ng2-datepicker>

With the right and left arrows, you can change the displayed month, while you can select another year, clear the date and get today’s date with a click of the mouse!

In my browser, the CSS is not displayed correctly. The layout is defined in a SASS file (ng2-datepicker/src/ng2-datepicker/ng2-datepicker.component.sass). But you can write your CSS to get your own customised layout!

Run your local server to admire your result!

ng serve -o

Thank you to jkuri for his useful date picker component!

See you next time for another article about Angular4 ! Follow me on Twitter, LinkedIn or Medium and take a look at our letsboot.com medium article series.

letsboot

Full Stack JavaScript development. And TypeScript and other stuff you need… A lot of Angular and Node.js…

F.Laurens

Written by

F.Laurens

Database and software developer, biology lover, scuba and free diver

letsboot

letsboot

Full Stack JavaScript development. And TypeScript and other stuff you need… A lot of Angular and Node.js…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade