Search code examples
angularangular-routingangular7snapshotnested-routes

Angular 7 Navigate to parent/:idChildroute/childroute, invoke data according to the route from a service


I have a component which has a scroll-able list for navigation, within that are 5 more components which show different information for the list item clicked, eg: When I click on a list item it opens a component with angular material mat-tab-group, there are 5 tabs and each has a router outlet in it. These tab components should show different parts of the data information invoked by click on the list item, more over if I paste

http://localhost:4200/audit/tabset/123/main

it should fetch the data of that route accordingly. the app routes should roughly look like this:

{
        path: 'audit', component: NavComponent,
        children: [
            { path: '', redirectTo: 'tabset', pathMatch: 'full' },
            {
                path: 'tabset', component: TabsetComponent,
                children: [
                    { path: '', redirectTo: 'Main', pathMatch: 'full' },
                    { path: '/:id/main', component: WorkOrderDetailComponent },
                    { path: '/:id/feed', component: FeedComponent },
                    { path: '/:id/operations', component: AuditformsmainComponent },
                    { path: '/:id/associated', component: AssociatedComponent },
                    { path: '/:id/settings', component: SettingsComponent },
                ]
            },
            { path: 'new-work-order', component: NewWorkOrderComponent },

        ]
    },

How do I achieve this?

Thank you in Advance


Solution

  • In each of your child components, for eg: main, feed, operations etc, do this:

    1) Import ActivatedRoute from @angular/router

    2) Inject ActivatedRoute in your constructor

    constructor(private route: ActivatedRoute){}
    

    3) Make sure your component class implements OnInit. Then, in your ngOnInit method, do the following to get the id:

    ngOnInit() {
      this.route.paramMap.subscribe(
      (params: ParamMap) => {
        this.id = params.get('id');
      }
     )
    }
    

    4) You will then have the id of the current product/item in this.id. You can then load the data using that.

    Let me know if this helps :)