angularangular-routerrouter-outlet

Angular router-outlet - Error: Cannot match any routes. URL Segment


I apologize in advance because I have seen several posts about this, but despite many attempts I can't solve my problem.

I am on Angular 13.3.9

I try to use the outlet router as described here: https://angular.io/api/router/RouterOutlet

My goal is to load components according to the routes at different places in the html code.

Here is the simplest code tried:

Router

const routes: Routes = [
  { path: 'challenge/pwd', component: ChallengePwd, outlet: 'challenge-pwd' },
  { path: 'identifier', component: Identifier, outlet: 'identifier' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html

<main>
    <section>
        <logo-loader></logo-loader>
        <section class="presentation">
            <router-outlet name="identifier"></router-outlet>
            <router-outlet name="challenge-pwd"></router-outlet>
        </section>
    </section>
</main>

When I try to access the url http://localhost:4201/identifier

I get an error : Error: Cannot match any routes. URL Segment: 'identifier'

I also tried encapsulating the outlet routes in a parent component like this:

const routes: Routes = [
  {
    path: 'oauth',
    component: MainPage,
    children: [
      { path: 'challenge/pwd', component: ChallengePwd, outlet: 'challenge-pwd' },
      { path: 'identifier', component: Identifier, outlet: 'identifier' }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html

<router-outlet></router-outlet>

main.page.html

<main>
    <section>
        <logo-loader></logo-loader>
        <section class="presentation">
            <router-outlet name="identifier"></router-outlet>
            <router-outlet name="challenge-pwd"></router-outlet>
        </section>
    </section>
</main>

But nothing works, I keep getting this error Error: Cannot match any routes. URL Segment: 'identifier'


Solution

  • I don't think It's a good way for achieving your goal. There is a working example for you

    First, you need a primary router, which doesn't have a name, so your routes should like this

          { path: 'oauth', component: OauthComponent },
          { path: 'challenge-pwd', component: ChallengeComponent, outlet: 'challenge-pwd' },
          { path: 'identifier', component: IdentifierComponent, outlet: 'identifier' },
    

    Unfortunately, the URL isn't friendly, you should respect the syntax

    /primaryRoute(routerOutletName:path)
    

    So un example of your URL should be

    http://localhost:4200/oauth(challenge-pwd:challenge-pwd)