Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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},
like image 948
Lahiru Mirihagoda Avatar asked May 16 '19 07:05

Lahiru Mirihagoda


3 Answers

You can simpally do it

{
    path        : '**',
    pathMatch   : 'full',
    component   : WrongRouteComponent
}

Put this wildcard route in your routing file at last in routes array.

I hope it helps you.

like image 62
Gurpreet Singh Avatar answered Oct 27 '22 00:10

Gurpreet Singh


Please change path '404' to **

So,the routes should be

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

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

];
like image 34
ahmeticat Avatar answered Oct 26 '22 23:10

ahmeticat


wild card route will catch all paths that you don’t know (undefined routes in your constant). Undefined URL causes the router to throw an error and crash the app.

Normally routes are read from top to bottom, that's why it's important to keep wild card route ('**') at the end of the route list. If you kept this on top, all the other routes will be taken as undefined.

You can use it as below.

{path: ‘not-found’ , component: ‘NotFoundComponent’}
{path: ‘**’ , redirectTo: ‘/not-found’}

Or

 { path: '**', component: NotFoundComponent}
like image 28
Denuka Avatar answered Oct 27 '22 00:10

Denuka