Angular 2在渲染元素后调用jQuery – 在使用API​​之后

我的Angular2应用程序使用RESTful API,然后根据结果创建一堆元素。 我试图在这些元素上调用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 } 

在我的模板中:

 ...blah blah 

这应该适合你:

 @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示例