bleenco/ng2-datepicker

Resetting a datepicker causes a jump, back to 1970

Opened this issue · 3 comments

I encountered this issue when I tried to add a clear button to the datepicker field, where the user can reset the input (the datepicker is used as a filter in a search function). Calling the datepicker's reset() method will set the default panel to the current date, but clicking on the previous or next month button will bring up December 1969 and February 1970 respectively.

Reproduction:
Call the reset() method of a default datepicker and then try to step to the previous or next month without selecting a date first.

It was a really strange and confusing behaviour so I started to track back the calling stack to find it's route. After debugging the behaviour in multiple scenarios

Here is what I found:
The reset() method sets the this.date variable to NULL, and while the current date is used as a fallback in the NgDatepickerComponent's init function (there is even a comment that indicates this: // this.date may be null after .reset(); fall back to current date.), the this.date variable does not get reassigned. After this if the user does not select a date value, just tries to step to the previous or next month then the prevMonth() and nextMonth() functions will still use the NULL value of this.date. But the NULL will be parsed as January 1970, and the subMonths() and addMonths() methods will return with December 1969 and February 1970, respectively.

Maybe I missed a best-practise about how to clear a datepicker but this does not seems like an intended behaviour either way.

Any help appreciated,
Thanks in advance!

jkuri commented

I do not have permissions to make a fix, please try this version of datepicker:
bleenco-ui-datepicker.zip

Thank you!
I am using the datepicker as a npm package and I would rather not include it as a component in my project if I do not necessarily have to. I will take a look nevertheless, thanks

For those running into this issue and waiting for it to be addressed, there is an easy workaround due to all the properties of the datepicker object being public -- create your own method to reset the variables correctly. If you set a view child property on the consuming component that references the datepicker, you can just write something like this:

@ViewChild('datepickerRef', { static: false }) datepickerRef: NgDatepickerComponent;

datepickerReset() {
        this.datepickerRef.date = new Date();
        this.datepickerRef.innerValue = null;
        this.datepickerRef.init();
}