Angular 2在渲染元素后调用jQuery - 在使用API之后 [英] Angular 2 calling jQuery after rendering elements - after consuming API
问题描述
我的Angular2应用程序使用RESTful API,然后根据结果创建一堆< select>
元素。我试图在这些< select>
元素上调用jQuery函数,但看起来jQuery函数执行得太晚了。我尝试将函数放在 ngAfterContentInit
中,但这不起作用。将它放入 ngAfterViewChecked
冻结了我的浏览器。
My Angular2 app consumes a RESTful API and then creates a bunch of <select>
elements based on the result. I'm trying to call a jQuery function on these <select>
elements, but it looks like the jQuery function executes too late. I tried putting the function in ngAfterContentInit
but that didn't work. Putting it in ngAfterViewChecked
froze my browser.
页面呈现后,如果我将jQuery函数粘贴到控制台中,一切正常,所以我知道我的功能和一切都是有用的。他们的订单可能搞砸了或者其他什么。
After the page has rendered, if I paste the jQuery function into the console, everything works, so I know that my function and everything are functional. Their order is just probably messed up or something.
在我的组件中:
ngOnInit() {
this.myService.getAll().subscribe(
data => this._data = data,
error => this._error = "invalid.");
}
ngAfterViewInit() {
$("select").select2(); // <--- jQuery function I need to execute after rendering
}
In我的模板:
<select *ngFor="let d of _data">...blah blah</select>
推荐答案
这应该适合你:
@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
这篇关于Angular 2在渲染元素后调用jQuery - 在使用API之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!