In Angular, a wildcard route is used to catch all undefined URLs and redirect users to a 404 page or a fallback component. This keeps your SPA user-friendly by handling invalid URLs gracefully instead of leaving users on a blank or broken page.
'**' matches any URL that doesn’t match a defined route.PageNotFoundComponent or a redirect.A wildcard route is defined inside the Angular Routes array using the path '**'. It is usually combined with either a component or a redirect configuration.
app-routing.module.ts
// App routing module with wildcard route for 404 handling
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const routes: Routes = [
{ path: '', component: HomeComponent }, // Default home route
{ path: '**', component: PageNotFoundComponent } // Wildcard route for unknown URLs
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
The wildcard route usually points to a simple, user-friendly 404 component. This component can display a message and optional navigation links back to the main parts of your app.
// Simple Angular component used for the 404 Page Not Found screen
import { Component } from '@angular/core';
@Component({
selector: 'app-page-not-found',
template: '<h2>404 - Page Not Found</h2><p>The page you are looking for does not exist.</p>'
})
export class PageNotFoundComponent { }
Instead of showing a separate 404 page, you can also redirect all unknown URLs back to a safe default route such as / (home) or /dashboard.
// Wildcard route that redirects unknown URLs to the home route
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: '**', redirectTo: '', pathMatch: 'full' } // Redirect all invalid paths to home
];
'**' will match.PageNotFoundComponent, the user sees a clear “404 - Page Not Found” message instead of a blank screen.redirectTo, Angular internally redirects the user to the specified route (for example, the home page).redirectTo).PageNotFoundComponent that includes a “Back to Home” button.redirectTo and test how it behaves compared to the component approach./random, /this/does/not/exist) in the browser and confirm that the wildcard route is triggered./about) and verify that it still works correctly when defined before the wildcard.