Custom 404 Error Page
Introduction: The Importance of a 404 Page
Welcome back! So far, you have learned how to create a reusable layout component and style your Cooking Helper frontend using TypeScript and Angular. Now, let’s talk about what happens when a user tries to visit a page that doesn’t exist on your site.
A “404 error” is what users see when they try to visit a page that isn’t found. By default, most web applications show a plain, unfriendly error message. This can be confusing or frustrating for users. A custom 404 page helps your site look more professional and guides users back to where they want to go.
In this lesson, you’ll learn how to create a custom 404 page for your Cooking Helper site using Angular. This will make your site more user-friendly and show that you care about the user experience.
Recall: Angular Templates and Routing
Before we start, let’s quickly remind ourselves how Angular uses component-based templates and handles routing.
- Templates: In Angular, each component has its own HTML template. This helps you organize your UI into reusable pieces.
- Routing: Angular uses a router to decide which component to display for each URL. If a user visits a URL that doesn’t match any route, you can show a special component for “not found” pages.
You’ve already used components and routes in previous lessons. Now, you’ll use these same ideas to handle errors in a friendly way.
Building the NotFoundComponent
Let’s start by creating the component for your custom 404 page.
Inside your Angular project, create a new folder called not-found inside src/app/pages/. Then, create two files: not-found.component.ts and not-found.component.html.
Here’s how your not-found.component.html file might look:
Let’s break this down:
- The
<section>contains the main message for the 404 page. - The
<h1>shows a big “404 - Page Not Found” message. - The
<p>gives a short explanation. - The
<a routerLink="/">provides a link to go back to the home page.
Now, create the not-found.component.ts file:
Here’s what’s happening:
- The
@Componentdecorator defines the component and its settings. imports: [RouterLink]allows you to use Angular’s router link in your template.templateUrlpoints to the HTML file you just created.styleUrlwill point to the CSS file for this component (we’ll create it next).
