Wildcard Routes in Angular
In Angular, wildcard routes are used to match any path, whether it is valid or not. If the user navigates to an “invalid” or “undefined URL”, you can use a wildcard route to catch that URL and navigate to a specified fallback component, such as Home, Login, or PageNotFound, depending on your application’s needs.
Wildcard routes are defined using a double asterisk (**) symbols. This special route matches any URL that doesn’t match any of the predefined routes in the route configuration.
Real-time Scenario
For example, if a user tries to access a path like /dashboard, which is not defined in the routes array, the wildcard route will match and can redirect them to a default or error component, such as a PageNotFound component.
Syntax of Angular Wildcard Routes
Below is the syntax to create a Angular Wildcard Routes −
const routes: Routes =[{ path:'**', component: SomeComponent }];
Here,
- **: The wildcard path that matches any URL, whether valid or invalid.
- SomeComponent: The component that will be rendered when the URL is invalid (e.g., Login, Home, or PageNotFound).
Example of Angular Wildcard Routes
Below is a example of using the Wildcard Routes in a Angular project −
Step 1: Create a pagenotfound component
ng generate ccomponent pagenotfound
Step 2: Define wildcard route
import{ Routes }from'@angular/router';import{ HomeComponent }from'./home/home.component';import{ AboutComponent }from'./about/about.component';import{ ViewItemComponent }from'./view-item/view-item.component';import{ PagenotfoundComponent }from'./pagenotfound/pagenotfound.component';exportconst routes: Routes =[{path:'home', component: HomeComponent},{path:'about', component: AboutComponent},{path:'view/:id', component: ViewItemComponent},{path:'**', component: PagenotfoundComponent}];
Step 2: Add your routes to your application
<h1>Angular Routing</h1><a routerLink="/home">Home</a><br><a routerLink="/about">About</a><a routerLink="/view/1">View Item1</a><br><a routerLink="/view/2">View Item2</a><router-outlet></router-outlet>
Now run the application and try to enter an invalid URL:

By observing the URL in the above GIF, you can see that whenever a user tries to access an invalid or undefined URL, it will automatically redirect to the “page not found” page.