I'm currently developing a solution for Angular 2 Bootstrap Datepicker to automatically close when a user clicks outside of it.
My current approach involves tracking external clicks and updating a boolean flag as shown below:
@Component({
selector: 'ngbd-datepicker-popup',
templateUrl: 'app/component/datepicker/datepicker.html',
host: {
'(document:click)': 'handleClick($event)'
}
})
export class NgbdDatepickerPopup {
private showDatePicker: boolean = true;
constructor(private elementRef: ElementRef) {}
handleClick(event: any) {
if (!this.elementRef.nativeElement.contains(event.target)) {
this.showDatePicker = false;
}
}
}
Although I can track the clicks and update the flag, I'm uncertain how to proceed in order to properly close the datepicker. The challenge lies in calling the close()
method from the markup where the datepicker is declared.
Here's the annotated markup:
<form class="form-inline" bindToBooleanFlagHere="d.close()"> <!--if true, close the popup --!>
<div class="form-group">
<div class="input-group">
<input type="text" style="z-index: 0;" readOnly class="form-control" placeholder="mm-dd-yyyy" firstDayOfWeek="1"
name="dp" [(ngModel)]="date" (ngModelChange)="dateChange(date)" ngbDatepicker #d="ngbDatepicker"> <!-- datepicker declared here --!>
<div *ngIf="!disableThis" class="input-group-addon" style="background-color: white; cursor: pointer" (click)="d.toggle()">
<i class="glyphicon calendar"></i>
</div>
</div>
</div>
</form>
In my HTML, the datepicker object is identified as d
while external clicks are tracked in the TypeScript component. Once the boolean flag showDatePicker
is set to false due to an external click, the markup needs to respond by invoking the d.close()
method.