我的 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>
最佳答案
这应该适合你:
@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();
});
});
}
关于javascript - Angular 2 在渲染元素后调用 jQuery - 在使用 API 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40938422/