Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when route changed and new view replaced in Angular

I am looking to detect when route changed and new view(html) replaced.

Tried below code but don't know how to proceed further.

this._routerSub = this.router.events
  .filter(event => event instanceof NavigationEnd)
  //.do(event => console.log(event)) // 
  .subscribe((value) => { });

Also tried below code but getting error

Argument of type Event is not assignable to parameter of type '(value:Event)=>void'.

   import { Router, NavigationEnd, Event  } from '@angular/router';

   this._routerSub = this.router.events  
      .subscribe(event : Event) => {
      if (event instanceof NavigationEnd) {
        console.log(event.url);
      }
    });

Vega below are my app.component.ts and app.component.ts code. Isn't it suppose to call onActivate on activate. As router outlet will emit an activate event any time a new component is being instantiated.

app.component.html

<router-outlet (activate)="onActivate($event)" ></router-outlet>

app.component.ts

   onActivate(e) {
        debugger;
        console.log(1);
      }
like image 844
Sunil Kumar Avatar asked Jun 04 '18 06:06

Sunil Kumar


People also ask

Which of the following will help you to detect a route change in Angular?

Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.

Is ngOnDestroy called on route change?

ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.

What does ActivatedRoute do in Angular?

ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.


1 Answers

How about using router-outlet exposed activate event:

<router-outlet (activate)="onActivate($event)"></router-outlet>

onActivate(e) {
  console.log(e.constructor.name);
  //etc... you can access to a lot of other information
}
like image 161
Vega Avatar answered Nov 15 '22 05:11

Vega