【问题标题】:Using jQuery with Angular2 inside *ngif is not working在 *ngif 中使用带有 Angular2 的 jQuery 不起作用
【发布时间】:2017-06-21 13:17:48
【问题描述】:

我的 Angular2 *ngIf 中有 Countdown 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());
        }
    }

结果: 仪表板

【问题讨论】:

  • 对A2不是很熟悉——但是不需要在ngIf中引用控制器吗?例如 - ngIf="sampleController.isDataAvailable"....
  • 其实我在这个标签里面也有一个标题,它只是显示标题(h1)而不是倒计时。

标签: javascript jquery angular typescript


【解决方案1】:

解决此问题的一种方法是在子组件中设置 jQuery 代码,以使其摆脱父组件对 ngIf 的限制。

【讨论】:

  • 你是怎么做到的?
【解决方案2】:

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

    // ...
  }
}

【讨论】:

    猜你喜欢
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 2017-10-10
    • 2016-04-14
    相关资源
    最近更新 更多