Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the selected date in ngx-bootstrap/datepicker which is launched when an icon is clicked into a common html input?

I have a common HTML date input, and next to it I have a font-awesome icon. This icon has the functionality of launching the bsDatePicker, however, the selected date is not stored anywhere. I'd like to know how could I make that the selected date is transferred to the date input?

This is the HTML code:

//this is the common html input
<input type="date" class="form-control">

//and this is the fa icon that launches the calendar
<em #dp="bsDatepicker" bsDatepicker class="fa fa-search"></em>

How can I store the selected date in a variable in my component, and then somehow make the input updates its value with it?

Thanks!

like image 711
Julio Rodríguez Avatar asked Jan 22 '26 07:01

Julio Rodríguez


1 Answers

Use [(bsValue)]="date" to bind the value of the bootstrap datepicker to a variable and [value]="date | date: 'yyyy-MM-dd'" to bind the value of the date input to the same variable:

<input type="date" class="form-control" [value]="date | date: 'yyyy-MM-dd'">
<em #dp="bsDatepicker" bsDatepicker class="fa fa-search" [(bsValue)]="date"></em>

Working demo: https://stackblitz.com/edit/ngx-bootstrap-datepicker-uqz2hr

Note that input uses a one-way binding, so updating the date in the input will not change the value of the variable (you can only change it with the datepicker). If you want the changes in the input to be saved as well, you need to add something like this:

<input type="date" class="form-control" [value]="date | date: 'yyyy-MM-dd'" 
       (input)="parseDate($event.target.value)">

and in ts:

public parseDate(e) {
  this.date = new Date(e);
}
like image 135
Kirill Simonov Avatar answered Jan 25 '26 05:01

Kirill Simonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!