Open In App
Related Articles

How to setup 404 page in angular routing ?

Like Article
Save Article
Report issue

To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple angular component called PagenotfoundComponent

Creating Component: Run the below command to create pagenotfound component.

ng generate component pagenotfound

Project Structure: It will look like this.

Implementation: Add the below code inside HTML template of this component to display a simple 404 error message.


    <h1>404 Error</h1>
    <h1>Page Not Found</h1>


Then inside the routing file, we have to provide this component route and make this available for every 404 requests. So, inside the app-routing.module.ts file, we have to create a new route for this PagenotfoundComponent.


import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PagenotfoundComponent } from 
import { PostCreateComponent } from 
import { PostListComponent } from 
const routes: Routes = [
    { path: '', component: PostListComponent },
    { path: 'create', component: PostCreateComponent },
    { path: 'edit/:postId'
        component: PostCreateComponent },
    //Wild Card Route for 404 request
    { path: '**', pathMatch: 'full'
        component: PagenotfoundComponent },
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule],
    providers: []
export class AppRoutingModule { }


Explanation: Here the route for PagenotfoundComponent is provided inside the routes array. Here any path except the provided routes is handled by this PagenotfoundComponent and our HTML template is displayed in the browser. So now if someone tries to send a request to any page that is not present in the routes array then that user is automatically navigated to this PagenotfoundComponent.

Steps to run the application: Run the following command to start the application:

ng serve

Now open the browser and go to http://localhost:4200, where everything is working fine. Now go to http://localhost:4200/anything, where we will get the 404 error as shown below.

Last Updated : 26 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads