Loading jQuery functions in Angular 2

What is the correct way to load jQuery functions in Angular 2?

I added jQuery to ngAfterViewInit . It works fine for one route, but if I switch to another (for example, from id: 1 to id: 2 ), it does not work for the second (I use the same component for both).

It works using ngAfterViewChecked , but then the function is executed several times (after each change in the view).

This is my jQuery function:

 $('.chips').on('chip.add', (e, chip) => { console.log(e, chip); }); 

Plunker

+6
source share
1 answer

One possible solution to your problem might look like this:

1) You need to import NgZone

 import { NgZone } from '@angular/core'; 

2) Add it to your constructor

 constructor( ... private ngZone: NgZone ) {} 

3) Add code that does the magic in your goTo method

 goTo(id) { this.router.navigate(['/detail', id]); if(id === 3) { this.ngZone.onMicrotaskEmpty.first().subscribe(this.ngAfterViewInit); } } 

Thus, when you go to 3 pages of ngAfterViewInit , the method will be executed after detecting changes

4) Remember to import the first statement:

 import 'rxjs/add/operator/first'; 

Here is an example of a plunger

+2
source

Source: https://habr.com/ru/post/1012475/


All Articles