Search code examples
javascriptangulartypescriptangular-routerangular8

Get the URL with Angular Router


I need to fetch my current route (using the Router) in a component (my Nav component) which is located in the App Component but as it's already loaded, it's not refreshing on a click and my function in the nav component isn't returning any new URL. How can I manage to have the new URL with my nav component ?

Here is my app component :

<app-nav></app-nav>
<body>
    <div class="container">
        <router-outlet></router-outlet>
    </div>
</body>

Here is my nav component (.ts) :

ngOnInit() {
    console.log(this.router.url);
    if(this.router.url == "/") {
      this.color = "large";
      this.logoPath = "assets/logos/w-logo-full.png";
    } else {
      this.color = "small";
      this.logoPath = "assets/logos/c-logo-full.png";
    }

It was working when my app-nav was in every component but it's not working anylonger since I've moved it..


Solution

  • you can use router service events observable

    app.component

      constructor( public router: Router,) {
      }
    
      public ngOnInit(): void {
        this.router.events.subscribe(e => {
    
    
          if (e instanceof NavigationEnd) {
            console.log(this.router.url);
            // ... 
          }
    
        });
      }
    

    NavigationEnd An event triggered when a navigation ends successfully.