6

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

5
  • Could you demonstrate it on a plunker? Commented Nov 19, 2016 at 3:59
  • Here's a Plunker. Commented Nov 19, 2016 at 5:00
  • Router reuses your component so constructor and ngAfterViewInit aren't firing Commented Nov 19, 2016 at 5:27
  • 1
    any ideas on how to make it work? Commented Nov 19, 2016 at 5:48
  • It works using ngAfterViewChecked but, then, the function is executed multiple times (after every change in the view) When you say $(.chips) you only refer to the already rendered elements. Any new element will require you to add it again and that is how it is supposed to work. Commented Nov 19, 2016 at 11:36

1 Answer 1

2

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

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

Comments

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.