1

I have a javascript function inside a file i route into an ng-view in an Angular project. Is there a way to execute said function after the routing has finished? similar to JavaScript's window.onload?

2
  • Which version of angular are you using? Commented Dec 12, 2019 at 6:37
  • In the route, a component will get loaded so why not call the function in its lifecycle hook. Commented Dec 12, 2019 at 6:37

2 Answers 2

2

Yes you can use a router event, In your constructor,

    constructor(private router: Router) {
      this.router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
         // call your function here
        }
      });
    }

Dont forget to import

import { Router } from '@angular/router';

This event is called only when the navigation is about to end.

**The sequence of router events is as follows,**
NavigationStart,
RouteConfigLoadStart,
RouteConfigLoadEnd,
RoutesRecognized,
GuardsCheckStart,
ChildActivationStart,
ActivationStart,
GuardsCheckEnd,
ResolveStart,
ResolveEnd,
ActivationEnd
ChildActivationEnd
NavigationEnd,
NavigationCancel,
NavigationError
Scroll

Here are all the navigation events you can look at the angular docs https://angular.io/api/router/Event

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

2 Comments

pardon my ignorance, but could you please point me to a resource where i can see more on this syntax? its unfamiliar to me and i cant seem to find any good explanation on it.
Please have look at this link angular.io/api/router/Event
0

You should use NavigationEnd method from the angular routing lifecycle like this:-

import { Router } from '@angular/router';

     constructor(private router: Router) {}

       ngOnInit() {
        this.router.events.subscribe(event => {
          if(event instanceof NavigationEnd) {
             **// CALL  YOUR  FUNCTION HERE**
          }
        })
      }

For more reference please visit angular navigation cycle demo

1 Comment

Glad to hear that

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.