Let’s pick a date with ng2-datepicker

F.Laurens
letsboot
Published in
2 min readJul 27, 2017

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

That’s it! We can now easily pick a date from a nice calendar!

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.

--

--

F.Laurens
letsboot

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