4

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>
2
  • How about calling ` $("select").select2();` in the subscribe? Commented Dec 2, 2016 at 19:00
  • No luck unfortunately.. Commented Dec 2, 2016 at 21:19

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

But wouldn't this only affect 1 <select> element? What if I had multiple?
Yeah it is only for select that is populated from service. If you want to apply it to all select then use your jquery selector

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.