Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading jQuery functions in Angular 2

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

like image 522
brians69 Avatar asked Nov 19 '16 03:11

brians69


1 Answers

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

like image 164
yurzui Avatar answered Oct 14 '22 10:10

yurzui