0

im using the bootstrap datepiker (http://bootstrap-datepicker.readthedocs.io/en/latest/index.html) in my angular 2 application and have some troubles with initializing.

using the following in my component works, but is not pretty

ngAfterViewInit(): void {
    setTimeout(function() {
      $('.date').each(function() {
        console.log($(this));
        $(this).datepicker({
          format: 'dd.mm.yyyy',
          autoclose: true,
          calendarWeeks: true,
          language: 'de-DE',
          todayHighlight: true
        });
      });
    }, 1000)
  }

is there a way without the dirty timeout of 1 second to get this working? If i do not have the timeout, the jQuery selector does not return anything and there is no output in the console.

Kyle Krzeski
  • 6,183
  • 6
  • 41
  • 52
user3740359
  • 395
  • 1
  • 6
  • 16
  • Have you tried the life cycle method `ngAfterViewChecked` by chance? – aug Jul 20 '17 at 10:23
  • yes. it works, but the ngAfterViewChecked is being called very often, so i end up making a lot of unneeded initializations. If I only initialize on the first call of ngAfterViewChecked, the jQuery selector still does not seem to find the DOM elements – user3740359 Jul 20 '17 at 11:00
  • Oh actually, try instead of doing setTimeout, in the `ngAfterViewInit` using `$(document).ready()`. See [this question](https://stackoverflow.com/questions/35728731/how-to-run-a-jquery-function-in-angular-2-after-every-component-finish-loading) – aug Jul 20 '17 at 11:18
  • unfortunatly this does not work but good idea nevertheless – user3740359 Jul 20 '17 at 11:21
  • Can you also show your html ? – Long Field Aug 17 '17 at 04:42

1 Answers1

0

The problem was that the datepicker was inside an *ngIf directive.

Solution was to use the @ViewChildren with a QueryList and initialize once the querylist changed (subscribe to changes event)

user3740359
  • 395
  • 1
  • 6
  • 16