Angular router redirection and 404 pages

Angular router redirection and 404 pages

In this tutorial, we are going to learn about how to redirect a user from one page to another page and how to handle not found pages.

Redirection

Redirection is a technique to move a user to a different page instead of the page they requested because the page they are asking is currently not available in the site.

Example:

Open your appRoutes array.

app.module.ts
const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  {path: 'contact-us', redirectTo: 'contact'}];

In the above code, we have added redirectTo property with value contact to contact-us route.

It means if any user tries to navigate contact-us path they have been redirected to the contact path.

If you try to redirect user whenever he or she clicks on a login button or form submission for that you can check out navigate method example

Notfound pages

Notfound pages help us to match the invalid paths which are not present on our website. if anyone tries to navigate that invalid path we are showing them a not found page instead of a blank page so that they can understand they are not in the correct path.

Open your terminal and run following command.

ng g c notfound

This above command will generate a notfound component.

Now we need to update our appRoutes array.

const appRoutes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'contact', component: ContactComponent },
  { path: 'contact-us', redirectTo: 'contact' },
  { path: '**', component: NotfoundComponent }];

Here we have added a path ** it means it matches all invalid paths in our app and show them a NotfoundComponent we just created.