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.
pagenotfound.component.html
< div >
< h1 >404 Error</ h1 >
< h1 >Page Not Found</ h1 >
</ div >
|
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.
app-routing.module.ts
import { NgModule } from '@angular/core' ;
import { Routes, RouterModule } from '@angular/router' ;
import { PagenotfoundComponent } from
'./pagenotfound/pagenotfound.component' ;
import { PostCreateComponent } from
'./posts/post-create/post-create.component' ;
import { PostListComponent } from
'./posts/post-list/post-list.component' ;
const routes: Routes = [
{ path: '' , component: PostListComponent },
{ path: 'create' , component: PostCreateComponent },
{ path: 'edit/:postId' ,
component: PostCreateComponent },
{ path: '**' , pathMatch: 'full' ,
component: PagenotfoundComponent },
];
@NgModule({
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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 May, 2021
Like Article
Save Article