RoutingModule best practices in Angular7

In this post we’ll explore further Angular module best practices. Although we’ll talk about routing, the main focus of the article is the concept of a RoutingModule.

A custom RoutingModule

This best practice is “official”, the default Angular project template includes a file called app.routing.module.ts. Let’s see this file and figure out the benefits it offers:

Not much happens here – an empty route array is created. It is passed to the RouterModule.forRoot call, and RouterModule itself is exported.

Let’s focus on the latter first – in the previous article about the SharedModule we saw the benefits of importing and re-exporting common module dependencies. The same goes on here, our own RoutingModule imports the stock Angular RouterModule, works with it, then re-exports it. Our app module will only have to import the custom RoutingModule, no need to import RouterModule as well.

The point of a custom RoutingModule is to handle complicated routing. Sure, we could set up everything in our app module, but it tends to become rather bulky after a certain number of dependencies. So we create separate modules (Shared, Routing, Core and Features) to offload some initializing code, and make the process easier to follow.

Let’s see a real-world RoutingModule:

Notice that it’s not super complicated either. In fact, there’s only two extra lines of code, two Route objects representing two lazily-loaded feature modules. Don’t worry about lazy-loading yet, we’ll cover it in a later post. Point is, RoutingModules only focus on setting up your route hierarchy.

If you have a lazy-loaded app, or a smaller one using eager-loading this file will not get too long. If you’ve more complex needs (multiple layers of parent-child routes, a huge app) then you can separate your routing into smaller files. Either way, routing is stored in one place and will be simple to reason about.

Source code

I’m maintaining and developing a repo on GitHub. It contains Angular7 best practices. Follow this link to the relevant part of the code.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s