angulartypescriptangular-routingangular2-modulesangular-component-router

Angular2 nested children routing does not find the route match


I have a menu with some buttons, when the user clicks on the menu, the page is directed to another page with list of buttons that have a link to another page.

Therefore my routing looks like this:

const routes: Routes = [
  {
    path: '',
    data: {
      title: 'Components'
    },
    children: [
      {
        path: 'departments/:fname',
        component: DepartmentsComponent,
        data: {
          title: 'Departments'
        },
        children: [
          {
            path: '/:dname/modules',
            component: ModulesComponent,
            data: {
              title: 'Modules'
            }
          }
        ]
      },
    ]
  }
];

So the user initially has the URL of:

components/departments/informatics

When the user clicks on any of the buttons inside the page, It should be directed to modules page with the parameter before it. For example:

components/departments/informatics/modules

Heree's how I do the routerlink:

<div class="row" *ngFor="let fac of _faculty">
  <ul>
    <li *ngFor="let dep of fac.Departments" class="checking">
      <a routerLinkActive="active" [routerLink]="[department ,'modules']">
      </a>
    </li>
  </ul>

I get: Error: Cannot match any routes. URL Segment

What am I doing wrong?


Solution

  • The child route should not start with slash '/'.

    The route of DepartmentsComponent contains :fname, and child contains :dname, so the expected route is 'departments/:fname/:dname/modules'. I guess you can remove :fname:

    const routes: Routes = [
      {
        path: '',
        data: {
          title: 'Components'
        },
        children: [
          {
            path: 'departments',
            component: DepartmentsComponent,
            data: {
              title: 'Departments'
            },
            children: [
              {
                path: ':dname/modules',
                component: ModulesComponent,
                data: {
                  title: 'Modules'
                }
              }
            ]
          },
        ]
      }
    ];
    

    *ngFor variable is dep, so the link should be [dep,...], not [department, ...].

    <li *ngFor="let dep of departments">
      <a routerLinkActive="active" [routerLink]="[dep ,'modules']">{{dep}}
      </a>
    </li>
    

    Here is an example: http://plnkr.co/edit/WvvCDwIind2QQXY88lay?p=preview

    edit: just realized :fname was faculty, but the same principle should apply.

    edit 2: plunker with solution without 2nd level child route: http://plnkr.co/edit/GJ0KBTIlPoloBr0cbEHS?p=preview