Search code examples
angularangular2-routing

angular routerLink redirects to component as expected, but later router.url not returning current URL


I have a link in my navbar About when I click on it from my homepage (/), browser redirects to /about route(About component) in my application(without reloading the page/tab) which is what I am looking for.

In the component About I have a requirement where I need to load the content dynamically depending on the Url that I am on. I tried many ways of getting the current Url but it always returns "/" or does not return anything at all. What I have and what I believe should work without any problem follows below:

Link on the navbar

<a [routerLink]="['/about/who-i-am']" class="media d-flex align-items-center">
                <div class="icon icon-shape bg-gradient-primary rounded-circle text-white">
                  <i class="ni ni-palette"></i>
                </div>
                <div class="media-body ml-3">
                  <h6 class="heading text-primary mb-md-1">Who I am</h6>
                  <p class="description d-none d-md-inline-block mb-0">Small 2 line text goes in here about yourself and your blog/articles.</p>
                </div>
              </a>

About Component ts file:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-navbar-hero-content-section',
  templateUrl: './navbar-hero-content-section.component.html',
  styleUrls: ['./navbar-hero-content-section.component.css']
})
export class NavbarHeroContentSectionComponent implements OnInit {

  isWhoIam : Boolean = false;
  isHome : Boolean = false;
  constructor(private router: Router) { }

  ngOnInit(): void {

    var currentUrl: string;

    // Current Path:  company 
    // this.route.url.subscribe(url => {
    //   currentUrl = url[0].path;
    // });


    currentUrl = this.router.url;//the problem is here with currentUrl always returning "/" or the URL I came to this component/page from.

    console.log("current URL : " + currentUrl); 



    switch(currentUrl)
    {
      case "/" : 
      case "/home" :
      {
        this.isHome = true;
      }

      case "/about/who-i-am" : {
        this.isWhoIam = true;
      }
    }

  }

}


Any idea what could be happening here, I tried different ways to get the currentUrl with using Location/document and even window, all of them seem to be returning the same /

UPDATE:

Now I realized that the code in the ngOnInit() does not even execute/run when I click the link. I added a Date.now() to the console.log and when I click back and forth between the '/about/who-i-am' and '/' I see that the console log displays the same timestamp in the browser, it does not even change.


Solution

  • One way to achieve this would be by using

    this.location.path()
    

    or in your case something like

    this.location.path().inlcudes('home')
    

    Location has to be imported

    import { Location } from '@angular/common';
    

    and added to the constructor

    private location: Location,
    

    Update - try adding this to ngOnInit:

     this.router.events.subscribe((evt) => {
          if (evt instanceof NavigationEnd) {
           // evt.url should update when the url gets updated
           // and you can use it whereever needed
          }
        });