Search code examples
angularangular-routerangular15

Angular route children with parent custom matcher


I'm trying to use a regex on the parent route and then also have child routes, so I tried this:

const barcodeRoute = () => (segments: UrlSegment[]) => {
    if (!segments.length)
        return null

    const segment = segments[0]
    return barcodeRegex.test(segment.path) ? {consumed: [segment], posParams: {barcode: segment}} : null
}

export const routes: Routes = [
    {
        component: DisplayRootComponent,
        matcher: barcodeRoute(),
        children: [
            {
                path: 'safety-assessment',
                loadComponent: () => import('./app/safety-assessment/safety-assessment/safety-assessment.component')
                    .then(x => x.SafetyAssessmentComponent)
            }
        ]
    }
]

The regex will match and display the DisplayRootComponent, but if I append /safety-assessment to the end of the route, it still goes to the DisplayRootComponent instead of SafetyAssessmentComponent.

All the other posts I've seen on this are solved by "consuming" part of the url segments, which I've done, so I'm not sure what I'm missing.

A very simplified example without matchers or lazy loading can be see at this StackBlitz.


Solution

  • I created a stackblitz with your code and it works as expected.

    Go to https://stackblitz.com/edit/angular-8-nested-routing-6xezhp?file=src%2Fapp%2Fapp-routing.module.ts,src%2Fapp%2Fhome%2Fhome.component.html

    then click the link at the bottom. If it's still not working for you, perhaps you need to look at your barcode regex.

    Update Based on your StackBlitz, I can see that you are not including <router-outlet></router-outlet> in your parent anywhere. That's why the child is not showing. When you have nested routes, the child doesn't replace the parent, it is shown in addition to the parent. If you want it to replace the parent, then the route should be a sibling of the parent, not a child of the parent.

    Here is an updated version of your StackBlitz showing the child. https://stackblitz.com/edit/stackblitz-starters-jyc1mv?file=src%2Fparent.component.ts,src%2Fmain.ts