【问题标题】:Angular 2 calling jQuery after rendering elements - after consuming APIAngular 2 在渲染元素后调用 jQuery - 在使用 API 之后
【发布时间】:2017-04-17 17:32:40
【问题描述】:

我的 Angular2 应用使用 RESTful API,然后根据结果创建一堆 <select> 元素。我试图在这些 <select> 元素上调用 jQuery 函数,但看起来 jQuery 函数执行得太晚了。我尝试将函数放在ngAfterContentInit 中,但没有奏效。将其放入 ngAfterViewChecked 会冻结我的浏览器。

页面渲染后,如果我将 jQuery 函数粘贴到控制台中,一切正常,所以我知道我的函数和一切正常。他们的订单可能只是搞砸了或其他什么。

在我的组件中:

ngOnInit() {
  this.myService.getAll().subscribe(
           data => this._data = data,
           error => this._error = "invalid.");
}

ngAfterViewInit() {
  $("select").select2(); // <--- jQuery function I need to execute after rendering
}

在我的模板中:

<select *ngFor="let d of _data">...blah blah</select>

【问题讨论】:

  • 在订阅中调用`$("select").select2();`怎么样?
  • 不幸的是没有运气..

标签: javascript jquery angular


【解决方案1】:

这应该适合你:

@ViewChild('select') selectRef: ElementRef;
constructor(private myService: MyService, private ngZone: NgZone) {}

ngOnInit() {
  this.myService.getAll().subscribe(data => {
    this.options = data;
    // waiting until select options are rendered
    this.ngZone.onMicrotaskEmpty.first().subscribe(() => {
      $(this.selectRef.nativeElement).select2(); 
    });
  });
}

Plunker Example

【讨论】:

  • 但这不会只影响 1 个&lt;select&gt; 元素吗?如果我有多个怎么办?
  • 是的,它仅适用于从服务中填充的选择。如果您想将其应用于所有选择,请使用您的 jquery 选择器
猜你喜欢
  • 2018-09-07
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 2017-01-25
  • 2011-10-09
  • 2011-02-17
  • 2014-10-14
  • 2019-02-20
相关资源
最近更新 更多