Hide the datepicker only when clicking outside

Salma Hamed picture Salma Hamed · Nov 18, 2016 · Viewed 8.3k times · Source

I am using ng2-bootstrap datepicker in my angular2 application. And I want to hide the datepicker popup on clicking outside. I tried the solution suggested in this question.

But it doesn't work right, when choosing a date or switching to the months/year dialog, it closes the datepicker.

After investigation I discovered that the cause of this problem is that event target returned on click was not in the element ref initially but it is obtained on click with ngIf in the datepickers component implementation.

Here is a plunker addressing the issue.

Any suggestions how to solve this ?.

Answer

AMagyar picture AMagyar · Nov 18, 2016

You need to change the click event to mousedown.

import {Component, Input, Output, ElementRef} from '@angular/core';

@Component({
    selector: 'my-datepicker',
    host: {
        '(document:mousedown)': 'onClick($event)',
    },
    template: `
      <label>{{label}}</label>
      <input [(ngModel)]="dateModel" class="form-control" (focus)="showPopup()" />
      <datepicker class="popup" *ngIf="showDatepicker" [(ngModel)]="dateModel" [showWeeks]="true"></datepicker>
  `,
    styles: [`
    .popup {
      position: absolute;
      background-color: #fff;
      border-radius: 3px;
      border: 1px solid #ddd;
      height: 251px;
    }
  `],
})
export class DatepickerComponent {
    @Input() dateModel: Date;
    private showDatepicker: boolean = false;

    constructor(private _eref: ElementRef) { }

    showPopup() {
        this.showDatepicker = true;
    }

    onClick(event) {
       if (!this._eref.nativeElement.contains(event.target)) {
           this.showDatepicker = false;
       }
    }
}

Check out this plunker