Search code examples
angulartypescriptangular-router

How to set up a route for custom 404 page in Angular Project


In my Angular project I have a component called 'wrongRouteComponent' for custom 404 page. When someone entered a non Pre-defined route, It should show the 'wrong-route.component.html'. I do not understand how to do this.

This is the 'app-rouring.module.ts' that I have used.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

// Required components for which route services to be activated
import { LandingComponent } from '../../components/landing/landing.component';
import { DashboardComponent } from '../../components/dashboard/dashboard.component';
import { UserprofileComponent } from '../../components/userprofile/userprofile.component';
import { WrongRouteComponent } from '../../components/wrong-route/wrong-route.component';

const routes: Routes = [
  { path: '', component: LandingComponent},
  { path: '/dashboard', component: DashboardComponent},
  { path: '/userprofile', component: UserprofileComponent},

  //Wrong route
  { path: '404', component: WrongRouteComponent},

];

Can anyone tell me what changes should I add to the

{ path: '404', component: WrongRouteComponent},

Solution

  • This is the answer that worked for me.

    const routes: Routes = [
      { path: '', component: LandingComponent},
      { path: '/dashboard', component: DashboardComponent},
      { path: '/userprofile', component: UserprofileComponent},
    
      //Wild Card Route
      { path: '**', pathMatch   : 'full', component: WrongRouteComponent},
    
    ];