Angular Router how does path-matching works

Discussão em 'Angular' iniciado por Olivier Boissé, Junho 9, 2025.

  1. I have an app containing 2 routes :

    const routes: Routes = [
    { path: "", component: HomeComponent },
    { path: "hero", component: HeroComponent }
    ];

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


    The documentation says :


    The path-matching strategy, one of 'prefix' or 'full'. Default is 'prefix'.


    By default, the router checks URL elements from the left to see if the URL matches a given path, and stops when there is a match. For example, '/team/11/user' matches 'team/:id'.


    The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.
    ​

    By default, the pathMatch is prefix, so I expected the first route { path: "", component: HomeComponent } to match everything as an empty string is a prefix of all paths.

    When I hit /hero in the browser, I can see the HeroComponent, when I hit /foo, I see an error in the logs saying the route was not found. So obviously the first route isn't picked by the angular router despite its default prefix path-matching.

    I also tried with these routes :

    const routes: Routes = [
    {
    path: "",
    redirectTo: "/hero",
    pathMatch: "prefix"
    },
    { path: "hero", component: HeroComponent }
    ];


    to reproduce the behavior described in the documentation


    Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.
    ​

    When I hit an empty url /, the redirection works fine and I'm redirected to the /hero path, I expected to have a endless loop.

    Here is the app on stackblitz using the angular v11.0.8

    Can someone explain me how does the angular router path matching works exactly ? How can I obtain a endless loop (just to understand how the router works, not for a real app) ?

    Continue reading...

Compartilhe esta Página