0

I have some third party JS scripts in angular app which has $(document).ready functions, At start everything works fine but when I change the routes via routerLink then some functionality does not work but when page is reloaded then it works.

I have tried importing JS files in angular.json and index.html.

Please help if you have any solution for this problem.

Thanks.

5
  • which library you are using? Commented Dec 14, 2018 at 10:49
  • 1
    You shouldn't use $(document).ready in your library but, in another way, in your app made in Angular -> Angular use its virtual DOM, putting some code between the real DOM and the Angular's one could cause a lot of errors, maybe this is your case. You shoul put your logic executed into the $(document).ready into some angular life-cycle. Commented Dec 14, 2018 at 10:50
  • I have some custom JS file which uses document.ready function is there any change I can do in custom js file ? Commented Dec 14, 2018 at 10:52
  • can you edit the third party js script? Commented Dec 14, 2018 at 11:01
  • What changes do I need to make Commented Dec 14, 2018 at 11:07

1 Answer 1

1

This happens because the page is fully loaded once and then only portions of the page are re-loaded when you navigate on your routes (SPA). So, the $(document).ready event is fired only once, when the page is loaded.

An workaround to achieve this is fire your third party script on your own in some angular life-cycle, for example, angular router NavigationEnd event:

this.router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
     // do your stuff here
  }
});

But this is bad, it's easy to lost control. This could be better if you encapsulate the third party library in some Angular component, e.g. a directive, to avoid $(document).ready pattern.

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.