bleenco / ng2-datepicker

Angular2 Datepicker Component
http://ng2-datepicker.jankuri.com
MIT License
311 stars 236 forks source link

Open datepicker programmatically with button click #326

Open LeXa777 opened 6 years ago

LeXa777 commented 6 years ago

Looks like the current implementation does not allow for the datepicker to be opened programmatically if the event was triggered by a click.

In my template I have a simple button like so:

<button (click)="toggleHandler()">Toggle</button>

and in my component I have the following in order to trigger the date picker

@ViewChild(NgDatepickerComponent) datePicker: NgDatepickerComponent;

toggleHandler() {
    this.datePicker.toggle()
}

Which I would assume should toggle the datePicker dropdown (and looking at the source code, I feel like my assumption is correct), however it only works if the dropdown is already opened (i.e. if you previously clicked the input box) but if the dropdown is currently closed, it will not open it.

Having a very quick look at the source code, I think I found the bit of code that stops the dropdown from opening:

@HostListener('document:click', ['$event']) onBlur(e: MouseEvent) {
    if (!this.isOpened) {
      return;
    }

    const input = this.elementRef.nativeElement.querySelector('.ngx-datepicker-input');

    if (input == null) {
      return;
    }

    if (e.target === input || input.contains(<any>e.target)) {
      return;
    }

    const container = this.elementRef.nativeElement.querySelector('.ngx-datepicker-calendar-container');

    if (container && container !== e.target && !container.contains(<any>e.target) && !(<any>e.target).classList.contains('year-unit')) {
      this.close();
    }
  }

Which code, if not mistaken, is responsible of closing down the drop down when there is a click event that originated from outside of the dropdown. I.e. it works correctly when the dropdown is already open and the user clicks outside, however, when I click my custom button in order to open the dropdown, the code thinks that the dropdown is already open (isOpened is true as this was triggered earlier by the button click).

So yeah, long story short, just wanted to confirm that this is a indeed a bug and I'm not doing anything silly or there is a known workaround to this. If indeed this is a bug, I could potentially volunteer to fix it.

h0m36r0wn commented 6 years ago

a quick hack for this problem is stop the click event propagation ... let say you have <button (click)="handleToggle($event);$event.stopPropagation()">Toggle ng date-picker