Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - Get current route and it's data

How to get the current route you're in and its data, children and parent?

If this is the route structure:

const routes: Routes = [
  {path: 'home', component: HomeComponent, data: {title: 'Home'}},
  {
    path: 'about', 
    component: AboutComponent, 
    data: {title: 'About'},
    children: [
      {
        path: 'company',
        component: 'CompanyComponent',
        data: {title: 'Company'}
      },
      {
        path: 'mission',
        component: 'MissionComponent',
        data: {title: 'Mission'}
      },
      ...
    ]
  },
  ...
]

If I am currently in CompanyComponent, how do I get my current route w/c is Company, get its parent w/c is about, its data and its siblings such as mission, etc.?

like image 622
jedion Avatar asked Jun 15 '18 14:06

jedion


People also ask

How do you find the current path in Angular 6?

Steps to get current route URL in Angular. Import Router,NavigationEnd from '@angular/router' and inject in the constructor. Subscribe to the NavigationEnd event of the router. Get the current route url by accessing NavigationEnd's url property.

How can you get the current state of a route in Angular?

There are many ways by which you can get a current Route or URL in Angular. You can use the router service, location service or window object to get the path. You can also listen to changes to URL using the router event or URL change event of the location service.


1 Answers

@Component({...})
export class CompanyComponent implements OnInit {

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

ngOnInit() {

  // Parent:  about 
  this.route.parent.url.subscribe(url => console.log(url[0].path));

  // Current Path:  company 
  this.route.url.subscribe(url => console.log(url[0].path));

  // Data:  { title: 'Company' } 
  this.route.data.subscribe(data => console.log(data));

  // Siblings
  console.log(this.router.config);
}
}
like image 128
Sid Avatar answered Oct 11 '22 18:10

Sid