Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect date selection in ng-bootstrap Datepicker on input field?

We use the ng-bootstrap Datepicker as Directive in our project:

<input class="form-control"
         name="dp" ngbDatepicker #d="ngbDatepicker" (blur)="d.close()" [(ngModel)]="model"
         (ngModelChange)="onDateSelected()">

The current behaviour is that onDateSelected() is called when a date in the datepicker is selected, as well as every time a change is made to the input field.

The desired behaviour is that onDateSelected() is called whenever the user clicks on a date in the datepicker or moves the cursor out of the <input> (i.e. blur).

My approach was to change (ngModelChange) to (blur):

<input class="form-control"
         name="dp" ngbDatepicker #d="ngbDatepicker" (blur)="d.close(); onDateSelected()"
         [(ngModel)]="model">

but this leads to onDateSelected() not being called, when a date is selected from the datepicker - which kinda makes sense, because the cursor is not inside the <input>. However, I could not find some sort of dateSelected-Event when searching the ng-bootstrap docs on which I could call onDateSelected():

<input class="form-control"
         name="dp" ngbDatepicker #d="ngbDatepicker" (blur)="d.close(); onDateSelected()"
/* missing -> */ (dateSelected)="onDateSelected()" /* <- */ [(ngModel)]="model">

Is there something I miss? Or maybe another way to implement this behaviour? I can't think of being the only one with this requirement...

like image 408
Florian Gössele Avatar asked Feb 21 '18 10:02

Florian Gössele


2 Answers

Here is the solution:

<input 
class="form-control"    
name="startDate" 
[(ngModel)]="startDate"
(dateSelect)="doSomething()"
(blur)="doSomething()"
ngbDatepicker 
#startDate="ngbDatepicker"
>

Here (dateSelect) handles choosing from the calendar picker and (blur) handles manually input when the input loses focus.

like image 166
brett Avatar answered Sep 23 '22 01:09

brett


Meanwhile, the issue has been closed and there will be a (dateSelect) event in 1.1.0: https://github.com/ng-bootstrap/ng-bootstrap/pull/2254

like image 44
Florian Gössele Avatar answered Sep 21 '22 01:09

Florian Gössele