How can I get route name from app.component?

Viewed 2085

In my app.component.ts I have the code below to get the route name, but I always get /. Does anyone know why? I expect to get for example home, contact.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor(private router: Router) {
    console.log(router.url);
  }
}
2 Answers

If you want to get the before initialized route you need to do the following.

 constructor( private route: ActivatedRoute, private router: Router, private url: LocationStrategy ) {}

  ngOnInit(): void {
     
        this.router.events.subscribe((event) => {
          console.log(event); // If you see the log here, You can get lot of events. So based on your requirement you can able to filter
          if (event instanceof NavigationStart) {
              console.log((event as NavigationStart).url);
          }
      });
    }
Related