Easily show an Angular material calendar to let the user pick a date value

The Angular Material library contains an amazing set of visual elements that we can use to speed up our Angular application development. They are usually pretty straightforward to use, and we can build complex structures without much hassle. But when trying to obtain a date value from the user, there's a date picker component that is not as flexible as we would like it to be. It contains an input and a button to show the calendar selector, and while it is useful in some circumstances, we may simply want to show a calendar selector when the user clicks somewhere and obtain a date value.

To make this process much easier, the turbogui-angular library contains a method on the dialogService that allows us to simply show the same material calendar component and obtain a value from the user. No visual components need to be added; we may use it after the user clicks anywhere we want.

Show a calendar date picker with Angular and Typescript (TS)

Install the turbogui-angular dependency by executing the following command at the root of your project:

npm install turbogui-angular

Then run the following code to show a calendar selector to the user and obtain the selected date:

import { DialogService } from 'turbogui-angular';

// Inject the required dialog service into your angular component
constructor(public dialogService: DialogService) {

}

// Call for the calendar date picker
this.dialogService.addDateSelectionDialog({
        width: '500px',
        title: "some title for the dialog or ignore this"
    }, (selectedDate) => {

    if(selectedDate !== null){

        let year = selectedDate.getFullYear();
        let month = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
        let day = selectedDate.getDate().toString().padStart(2, '0');

        console.log(`${year}/${month}/${day}`);
    }
});

it is that easy. You call the addDateSelectionDialog() from the dialogService and then obtain the date from the user at the callback method via the selectedDate parameter (which will contain a Date() object). if the user decides not to choose any date, selectedDate will be null.