Creating a Module

In this lesson, we'll learn how to create a module with routing capabilities.

Like anything else, modules can be created with the Angular CLI. It’s the preferred and recommended way to create a module. We can run the ng generate module <name> command. The <name> portion can be replaced with the name of the module you’d like to give.

Project overview

The project we will be working on is a simple website. We’ll have a homepage, an about page, and a contact page. This is why we installed the router. We want to be able to switch between pages like a standard website.

If we want to, we can write everything in the AppComponent. However, that defeats the purpose of using Angular. Angular’s job is to help us split our codebase into separate files. This way, things are manageable.

One solution is to write one component per page. This works and is an entirely acceptable solution. One problem with this approach, however, is that it doesn’t scale as well. Some pages may be more complicated than others. When you have complex pages, you’ll want to break things down into smaller components.

If we just used components, the app module would have a long list of components registered under it. This would mean that other pages would have access to those modules. This can cause issues, such as longer loading times and namespace conflicts.

Therefore, it’s much better to write one module per page. Then, we can register a component to that module. This is the approach we’ll be taking.

Generating modules

Let’s create three modules for each page. In the command line, run the following commands:

For the homepage:

ng generate module home --routing

For the about page:

ng generate module about --routing

For the contact page:

ng generate module contact --routing

Here’s what the project will look like:

Get hands-on with 1200+ tech skills courses.