Angular 2在渲染元素后调用jQuery - 使用API之后
问题描述:
我的Angular2应用程序使用RESTful API,然后根据结果创建一堆<select>
元素。我试图在这些<select>
元素上调用jQuery函数,但它看起来像jQuery函数执行得太晚。我试着把这个功能放在ngAfterContentInit
里,但是那没有奏效。把它放在ngAfterViewChecked
冻结我的浏览器。Angular 2在渲染元素后调用jQuery - 使用API之后
页面呈现后,如果我将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();
});
});
}
怎么样调用'$(“选择”)。select2();'在订阅? –
不幸运.. – 7ball