angular6angular-routerangular-activatedroute

Angular 6 - Get current route and its 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.?


Solution

  • @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);
    }
    }