Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - Angular 2 calling jQuery after rendering elements - after consuming API

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...