Skip to content
Related Articles

Related Articles

Improve Article

How to setup 404 page in angular routing ?

  • Last Updated : 26 May, 2021

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 },
  
    //Wild Card Route for 404 request
    { 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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :