drbishop drbishop - 1 year ago 138
jQuery Question

Loading jQuery functions in Angular 2

What's the proper way for loading jQuery functions in Angular 2?

I've added my jQuery to

. It works fine for one route, but if I navigate to another one (e.g. from
id: 1
id: 2
), it doesn't work for the second one (I'm using the same component for both).

It works using
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);


Answer Source

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

    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 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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download