404 Page & Redirection - Wildcard Route , Router Navigate
What is a 404 Page?
A 404 page is shown when a user enters a URL that does not exist in the application.
Create Page Not Found Component
ng generate component pages/page-not-found
Page Not Found Component (page-not-found.ts)
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterLink } from '@angular/router';
@Component({
selector: 'app-page-not-found',
standalone: true,
imports: [CommonModule, RouterLink],
templateUrl: './page-not-found.html',
styleUrl: './page-not-found.css'
})
export class PageNotFound {}
Wildcard Route (app.routes.ts)
import { Routes } from '@angular/router';
import { PageNotFound } from './pages/page-not-found/page-not-found';
export const routes: Routes = [
{ path: '', component: Home },
{ path: 'login', component: Login },
{ path: 'about', component: About },
{ path: 'profile', component: Profile },
{ path: '**', component: PageNotFound }
];
Note:
Wildcard route (**) must always be last.
Redirect Instead of Showing 404 Page
{ path: '**', redirectTo: '' }
Use either component or redirectTo, not both.
Redirect on Button Click (Programmatic Navigation)
Home Component Import
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
standalone: true,
imports: [CommonModule],
templateUrl: './home.html'
})
export class Home {
constructor(public router: Router) {}
goToProfile() {
this.router.navigate(['profile']);
}
}
Interview Points
- 404 page is handled using wildcard route (
**) - Wildcard route should be last
RouterLinkis used for template navigationRouter.navigate()is used for button click navigation