Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery with Angular2 inside *ngif is not working

I have Countdown jQuery function inside my Angular2 *ngIf and it is not working. I don't have any error in my console.log, but the div is empty. It's just showing the title (h1). Here is my code: HTML

<div class="row" *ngIf="isDataAvailable"><h1>Dashboard</h1><div id="kodeCountdown"></div></div>

Angular2 TypeScript Component

ngOnInit() {
     this.getData().then(() => this.isDataAvailable = true); 
}
ngAfterViewInit() {
        if ($('#kodeCountdown').length) {
            var austDay = new Date();
            austDay = new Date(2017, 3, 2, 12, 10);
            jQuery('#kodeCountdown').countdown({ until: austDay });
            jQuery('#year').text(austDay.getFullYear());
        }
    }

Result: Dashboard

like image 421
Jose Carlos Santos Junior Avatar asked Feb 05 '23 04:02

Jose Carlos Santos Junior


1 Answers

The problem is that the ngAfterViewInit method is only called once after the component's view has been initialized. Since the *ngIf condition hasn't been evaluated to true when ngAfterViewInit is called, your #kodeCountdown element isn't visible which means that your countdown function isn't initialized.

One way to resolve this would be to execute that logic inside of the ngAfterViewChecked method (instead of the ngAfterViewInit method ), because then your code will be executed after *ngIf has been evaluated:

ngOnInit() {
  this.getData().then(() => this.isDataAvailable = true);
}
ngAfterViewChecked() {
  if ($('#kodeCountdown').length) {
    var austDay = new Date();
    austDay = new Date(2017, 3, 2, 12, 10);
    jQuery('#kodeCountdown').countdown({
      until: austDay
    });
    jQuery('#year').text(austDay.getFullYear());
  }
}

However, since the ngAfterViewChecked method is called after every check of the component's view, you will need to add additional logic to ensure that your countdown logic is only implemented once. You could simply set a flag to handle that:

private isCountdownInitialized: boolean;

// ...

ngAfterViewChecked() {
  if (!this.isCountdownInitialized && $('#kodeCountdown').length) {
    this.isCountdownInitialized = true;

    // ...
  }
}
like image 156
Josh Crozier Avatar answered Feb 07 '23 17:02

Josh Crozier