nestedangular5angular-routingangular-routernested-views

Angular 5 routing with nested components


OK So for sake of simplicity lets say I have 3 components: a parent component and two other components (child A and child B).

I want parent component to have an url prefix of '/parent' and contain one of the two other components, component A by default, else B, who have their own url prefixes of 'childA' and 'childB' respectively. Also I do not want parent component to to be viewable by itself, it must have either childA or childB viewable and if '/parent' is called it will automatically re-route to '/parent/childA'.

So far this is what I have in my router and it is not working I am getting an invalid path error on the console when I route to '/parent' and when I route to '/parent/child[AorB]' my browser lags forever and never routes:

{
  path: 'parent', component: ParentComponent,
  children : [
    {
      path: '',
      redirectTo: 'childA' 
    },
    {
      path: 'childA',
          component: ChildAComponent
    }, {
      path: 'childB',
      component: childBComponent
    }
  ]
}

parent's template is just a router-outlet like so:

<router-outlet></router-outlet>

Solution

  • Needed to add pathMatch: 'full' like so:

    {
      path: 'parent', component: ParentComponent,
      children : [
        {
          path: '',
          redirectTo: 'childA',
          pathMatch: 'full' //<--------- Need this here
        },
        {
          path: 'childA',
              component: ChildAComponent
        }, {
          path: 'childB',
          component: childBComponent
        }
      ]
    }