Angular 2 calling jQuery after rendering elements - after consuming API

穿精又带淫゛_ 提交于 2019-12-17 13:22:36

问题


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.

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.

In my component:

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 my template:

<select *ngFor="let d of _data">...blah blah</select>

回答1:


This should work for you:

@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



来源:https://stackoverflow.com/questions/40938422/angular-2-calling-jquery-after-rendering-elements-after-consuming-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!