Angular 2在渲染元素后调用jQuery

编程入门 行业动态 更新时间:2024-10-13 06:21:15
本文介绍了Angular 2在渲染元素后调用jQuery - 在使用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示例

Plunker Example

更多推荐

Angular 2在渲染元素后调用jQuery

本文发布于:2023-10-09 05:41:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474859.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   Angular   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!