微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在* ngif里面使用带有Angular2的jQuery是行不通的

我的Angular2 * ngIf里面有倒计时jQuery函数,它无法正常工作.我的console.log中没有任何错误,但div为空.它只是显示标题(h1).
这是我的代码
HTML

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

Angular2 TypeScript组件

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

结果:
仪表板

解决方法:

问题是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;

    // ...
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐