Angular Js

Explain Route Matching Mechanism used by Angular

Explain Route Matching Mechanism used by Angular

Route Matching Mechanism used by Angular?

This Article helps you to Understand, How Route Matching Mechanism used by Angular?

Angular applications require to redirect route and pathMatch is a property which informs a router how to match and map a URL to the path of an actual route.

As per route definition specified in routing module when URL has /home as path it will be handled by following route definition.

{path: 'home', component: HomeComponent},

HomeComponent is the component that will be called to handle this route.

Following route definition sets up a redirect to the above definition for home route if path matches '' (i.e. nothing after the base URL).

 {path: '', redirectTo:'/home', pathMatch: 'full'},

In the above route definition pathMatch value is used as ‘full’ which means value specified with path will be matched fully with the path after the base URL.

Another value for pathMatch is ‘prefix’ which tells the Angular to check if the path in the URL starts with the value given with path or not.

  {path: '', redirectTo:'/home', pathMatch: 'prefix'}

Now every path matches this route definition because technically every path starts with ''.

const routes: Routes = [
    {path: 'home', component: HomeComponent},
    {path: 'account', component: AccountComponent},
    {path: '', redirectTo:'/home', pathMatch: 'prefix'},
    {path: 'service', component: ServiceComponent}

In this example you will never be able to reach ServiceComponent because localhost:4200/service will always be matched by the redirect route. Other two routes above the redirect route will work fine because of the route ordering followed by Angular.

Route order in Angular
Angular uses the first-match wins strategy when matching routes so more specific routes should be placed above less specific routes.

Routes with a static path should be placed first.
Then an empty path route which matches the default route.
The wildcard route should be placed last because it matches every URL.

That's all for this topic Path Redirection in Angular Routing. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.