Search code examples
angulartypescriptroutesangular2-routingangular4-router

Dynamic Routing with tabs in angular2 4


Today I came across routing problem where I need help from you guys,

Actually, I am having a sidebar in which I have dynamic tree view navigations like below & right side I have 4 tabs default tab1 will be selected in which I am showing the data of active link

Link1
--sublink1
--sublink2
----sub2link1
------sub3link1
Link2
Link3
--sublink1
----sub2link1

Like above I having Nth submenus, for this, I have created a route

{ path: '**', component: tab1}

when I visit Link "link1/sublink2/sub2link1" default it will be a tab1 component

Now my question is if I want to navigate to tab2 component with the same link then how my route url should be.


Solution

  • Am answering my own question I solved it by using QueryParameter below is my approach:

    My Routing module will be:

    const routes: Routes = [
    {
      path: 'parent',
      component: parentComponent,
      children: [
        { path: '', component: allChildComponent},
        { path: '**', component: allChildComponent}
      ]
    }
    ];
    

    So this will accept navigation till N number of tree route like /parent/child/sub_child1/sub_child2/../../.... to navigate just use

    this.router.navigate(['/parent/child/sub_child1/sub_child2/../../....']);

    Now if we want to pass the parameters to ** route then you need to use query parameter which will look like below while navigating

    this.router.navigate(
       ['/parent/child/sub_child1/sub_child2/../../....'],
       {queryParams: 
           {param1: 'value1', param2: 'value2'}
       }
    );
    

    And finally, you can read this parameter in the component like below

    constructor(private route: ActivatedRoute) { }
    
    ngOnInit() {
      this.sub = this.route.queryParams
        .subscribe(params => {
          console.log(params);
        });
    }