What is Wildcard Route in Angular?
The Wildcard Route is basically used in Angular Application to handle the invalid URLs. Whenever the user enter some invalid URL or if you have deleted some existing URL from your application, then by default 404 page not found error page is displayed. In such scenarios instead of showing the default error page, if you also show a custom error page and this is possible by using the Angular Wildcard Route.
How to use Wildcard Route in Angular?
A Wildcard route has a path consisting of two asterisks (**). It matches every URL, the router will select this route if it can’t match a route earlier in the configuration. A Wildcard Route can navigate to a custom component or can redirect to an existing route. The syntax to use Wildcard Route is given below
{path:'**',component:InvalidComponent}
Example
Follow previous example first,
Next make the below changes to AppModule.ts
Now, we need to create a Invalid Link, so on clicking on the invalid link it should redirect
to InvalidUrl Component.
.HTML Changes
<h2>https://dotnetbyudayrajakonda.blogspot.com/</h2>
<nav class="navbar navbar-inverse">
<ul class="nav navbar-nav">
<li>
<a routerLink="home" routerLinkActive="active c1">Home</a>
</li>
<li>
<a routerLink="about" routerLinkActive="active c1">About</a>
</li>
<li>
<a routerLink="contact" routerLinkActive="active c1">Contact</a>
</li>
<li>
<a routerLink="services" routerLinkActive="active c1">Services</a>
</li>
<li>
<a routerLink = "invalidLink" routerLinkActive="active c1">Invalid Link</a>
</li>
</ul>
</nav>
<hr>
<router-outlet></router-outlet>
<h4 class="navbar-fixed-bottom">copyrights© reserved to my blog</h4>
Now, on clicking on the Invalid Link, it should redirect to customerrorcomponent
that is invalidcomponent
Note: If you add the Wildcard Route as the first route in Router Configuration then no other routes will be reached as the Wildcard Route always matched
Order of Routing
The order of the routes is very important. When matching routes find, the angular router uses first-match wins strategy. So more specific routes should be placed above less specific routes. So, Routes with a static path should be placed first, followed by the empty path route, that matches the default route.
No comments:
Post a Comment
Thank you for visiting my blog