Search code examples
angularangular-router

(Angular 5+) Getting data from child routes


I want to make breadcrumb for my app, so I put "title" on my data routes like this one:

export const appRoutes: Routes = [
    { path: 'home', component: HomeComponent },    
    {path: 'help', component: HelpComponent },
    {
        path: 'admin',
        component: AdminComponent,
        runGuardsAndResolvers: 'always',
        data: { title: "Admin"},
        canActivate: [AuthGuard],
        children: [
            {
                path: 'organisation', 
                component: ListOrganizationComponent, 
                data:{title: "Organisation"}, 
                resolve: {organizations: ListOrganizationResolver}
            }        
        ]
    },
    { path: '**', redirectTo: 'home', pathMatch: 'full' },
];

export class AdminComponent implements OnInit {
    title: string = "";
    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
      this.title = this.route.snapshot.data.title;
    }
}

When I run the code and go to: localhost:4200/admin/organisation only title from admin show up (title = "Admin"). I want to get title Organisation from child route .. how to do that ? And is there easy way to make breadcrumb in angular ?


Solution

  • You can use the firstChild property on your ActivatedRoute to retrieve the firstChild route and then go ahead and retrieve the data as you would for the current route. Here's an example:

    export class AdminComponent implements OnInit {
      breadcrumb: string;
    
      ngOnInit() {
        let breadcrumb = this.route.snapshot.data['title'];
    
        if (this.route.snapshot.firstChild) {
            breadcrumb += ' > ' + this.route.snapshot.firstChild.data['title'];
        }
    
        this.breadcrumb = breadcrumb;
      }
    
      constructor(private route: ActivatedRoute) {}
    }
    

    Here's a working demo. Be sure to navigate to /admin/organization.

    For your second question, you could try out ngx-breadcrumbs as the other answer mentioned.