Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

angular - How to detect bootstrap datetimepicker change events within angular2

I am using the bootstrap datetimepicker in angular 2

https://eonasdan.github.io/bootstrap-datetimepicker/

In my template i have:

<div class='input-group date datepicker'>
         <input type='text' class="form-control" [(ngModel)]="date">
         <span class="input-group-addon">
         <span class="glyphicon glyphicon-calendar" (click)="getCalendar()"></span>
       </span>
   {{date}}
</div>

The problem is when I select a date on the calendar by click, it does not trigger any "change" event (in other words, ngModel is not fired). If i type in the text box, then the {{date}} shows me the value plus the text i typed.

How can I detect changes on the text box if the user clicks on a date in the selector to change it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that Angular doesn't know that the input's value has changed in order to update ngModel. Another weird thing is that bootstrap-datetimepicker doesn't trigger the change event on the input - this requires some workaround.

See this working example:

<div class='input-group date datepicker'>
  <input type='text' class="form-control" #datePicker [ngModel]="date" (blur)="date = datePicker.value">
  <span class="input-group-addon">
    <span class="glyphicon glyphicon-calendar" (click)="getCalendar()"></span>
  </span>

  {{date}}
</div>

Notice the changes:

  • [ngModel]="date": we only need one-way data binding (from model to view) since Angular doesn't know when the input's value has changed
  • #datePicker: I've created a local variable in order to access its value
  • (blur)="date = datePicker.value": on blur we update the model

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...