A Bootstrap Datepicker for Aurelia using Typescript and Webpack

This tutorial will show how to add a Bootstrap Datepicker to an Aurelia project using Typescript and Webpack. The datepicker will be created as a custom component. Starting point for the tutorial is the Aurelia 'skeleton-typescript-webpack' project available on Github.

Add dependencies


We'll start by adding the required dependencies to the project. The Bootstrap datepicker depends on the Moment library to format dates so we have to install both of them. We also need to run the 'npm install' and 'typings install' commands as usual.

    
        npm install
        npm install moment --save
        npm install bootstrap-datepicker --save
        typings install
    

Create a custom component


First create the 'date-picker.html' file and add the following content:

    
        <template>
        <input class="datepicker" data-provide="datepicker" value.bind="value">
        </template>
    

Then create the 'date-picker.ts' file and add the content:

    
        import {inject, customElement, bindable} from 'aurelia-framework';
        import 'bootstrap-datepicker';

        var moment = require('moment');

        @inject(Element)
        @bindable('value')
        export class DatePicker {

        @bindable format = 'yyyy-mm-dd';

        constructor(element) {
        this.element = element;
        }

        attached() {

        $(this.element).find('.datepicker')
        .datepicker({
        format: this.format,
        startDate: '2000-01-01',
        autoclose: true,
        todayBtn: 'linked',
        todayHighlight: true
        })
        .on('changeDate', (e) => {
        this.value = moment(e.date).format("YYYY-MM-DD");
        });
        }
        }
    

Add the new custom component to the 'welcome.html', also add a require for the component:

    
        <template>
        <require from="date-picker"></require>
        ...
        <date-picker value.two-way="birthDate"></date-picker>
    

Add styling


The final step is to add the styling. Find the 'bootstrap-datepicker3.css' in the node_modules bootstrap-datepicker dist directorory and copy it to the 'styles' directory. Then we can customize colors etc to our likings. Finally in the 'main.ts' file, add an import for the css:

    
        import '../styles/bootstrap-datepicker3.css';
    

Run it


Now we are ready to the run the application using 'npm run dev' command. The completed code can be found here.