What's the proper way for loading jQuery functions in Angular 2?
I've added my jQuery to ngAfterViewInit
. It works fine for one route, but if I navigate to another one (e.g. from id: 1
to id: 2
), it doesn't work for the second one (I'm using the same component for both).
It works using ngAfterViewChecked
but, then, the function is executed multiple times (after every change in the view).
This is my jQuery function:
$('.chips').on('chip.add', (e, chip) => {
console.log(e, chip);
});
Plunker
One possible solution for your problem might look like this:
1) You need to import NgZone
import { NgZone } from '@angular/core';
2) Inject it in your constructor
constructor(
...
private ngZone: NgZone
) {}
3) Add some code that does some magic in your goTo
method
goTo(id) {
this.router.navigate(['/detail', id]);
if(id === 3) {
this.ngZone.onMicrotaskEmpty.first().subscribe(this.ngAfterViewInit);
}
}
This way when you go to 3 page ngAfterViewInit
method will be executed after change detection
4) Don't forget to import the first
operator:
import 'rxjs/add/operator/first';
Here's Plunker Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With