NAD
NAD

Reputation: 33

calling javascript function after angular routechange

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?

Upvotes: 1

Views: 654

Answers (2)

anonymous
anonymous

Reputation: 1681

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

Upvotes: 2

siddharth shah
siddharth shah

Reputation: 1147

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

Upvotes: 0

Related Questions