Search code examples
angularchildrenangular-routerangular10

Angular 10 matcher children not showing children


I'm trying to create a route pattern like this:

/element << -- show list of elements

/element/1 <<-- show detail of element 1

/element/1/child <<-- show list of children of element 1

I tried the path property ":id" and "child" but it's not working the children, neither the url, I changed it to use matchers, and first the url changed correctly to /element/1/child but the component shown is the parent even when the children matcher working with the url and also consuming well.

Do I need to do something else? or is it a problem with mathcers?

const routes: Routes = [
  {
    path: "",
    children: [
      { path: "", redirectTo: "/base", pathMatch: "full" },
      {
        path: "base",
        component: BaseComponent
      },
      {
        // path: ":id",
        matcher: (url) => {
          return url.length === 1
            ? {
                consumed: url.slice(0, 1),
                posParams: { id: new UrlSegment(url[0].path, {}) }
              }
            : { consumed: [] };
        },
        component: ParentComponent,
        children: [
          {
            // path: "child",
            matcher: (url) => {
              const result =
                url.length > 0
                  ? {
                      consumed: url,
                      posParams: { parentId: new UrlSegment(url[0].path, {}) }
                    }
                  : null;
              console.log("children entered", url); // it's entering
              console.log("consumed", result); // and consuming ok
              return result;
            },
            component: ChildrenComponent
          }
        ]
      }
    ]
  }
];

Example Code: https://codesandbox.io/s/cool-star-nr67j?file=/src/app/app.module.ts

enter image description here


Solution

  • The only thing that's missing is an router-outlet in the parent.component.html:

        <div>--- Parent ({{ id }}) ---</div>
        <div><a routerLink="/">Back</a></div>
        <a routerLink="/1/child">Child</a>
    
        <router-outlet></router-outlet>
    

    There is a lot as to why this is needed, but a rule of thumb would be that a component from a route configuration which also has the children property must have at least one router-outlet. It is at least because you can have named outlets as well.

    CodeSandiox demo.