2017-02-04 51 views
2

我在我的Angular2 * ngIf里面有Countdown jQuery函数,它不工作。我的console.log中没有任何错误,但是div是空的。它只是显示标题(h1)。 这里是我的代码: HTML使用jQuery与Angular2里面* ngif不工作

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

Angular2打字稿组件

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()); 
     } 
    } 

结果: 仪表板

+0

不是很熟悉A2 - 但是你不需要在ngIf中引用控制器吗?例如 - ngIf =“sampleController.isDataAvailable”.... – gavgrif

+0

其实我在这个标签里面也有一个标题,它只是显示标题(h1)而不是倒数。 –

回答

4

的问题是,ngAfterViewInit method只调用组件的视图有一次后已初始化。由于调用ngAfterViewInit*ngIf条件尚未评估为true,因此您的#kodeCountdown元素不可见,这意味着您的倒计时功能未初始化。解决这个

的一种方法是执行ngAfterViewChecked method的内部的逻辑(而不是ngAfterViewInit method),因为那时你的代码将*ngIf进行了评估后执行

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()); 
    } 
} 

然而,由于每次检查组件视图后都会调用ngAfterViewChecked方法,因此需要添加其他逻辑以确保倒计时逻辑仅实现一次。你可以简单地设置一个标志来处理:

private isCountdownInitialized: boolean; 

// ... 

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

    // ... 
    } 
}