Setting up Routing in a multi-module Angular 4 app using the Router module

Andreas Stamataris
2 min readJan 25, 2018

--

The purpose of this article is to provide clear guidelines on how to set up routing in your angular app if it contains multiple self-contained modules (which it probably does or will do in the future). The angular.io guide for this also pretty good but I’m writing this to aid my learning of the subject, and hopefully help some other people while I’m at it. I will also try to be more concise.

Prerequisites:

  1. This guide assumes some basic knowledge of Angular routing ( <base href> , <router-outlet> etc. If you are not familiar with those, you can read more about it here.
  2. An Angular 4+ app created via the Angular CLI
  3. One or more modules besides the AppModule (generated by the CLI by default). I will refer to the extra module as secondary module, with the AppModule being the primary module.
  4. [Optional] One or more components in the new Module

Step 1: Give your secondary module its own module file.

This will allow for the modularisation of your app as you will deal with each module individually and import the module(along with its Routes) in your app.module.ts file. Just to clarify, the secondary module is expected to have one or more components which will be added to it and will act as a ‘hub’ for those components.

Step 2: Create a routing module for your secondary module

Instead of declaring the routes in our secondary.module.ts file, we will create a file to hold our module routes. This will be done for the app.module.ts too.

Step 3: Import the secondary routes into the respective secondary module.ts file

This step is pretty simple and self-explanatory.

[Optional] Step 4: Create a routing module for your primary module

This step is optional as you can define your routes in your app.module.ts but for consistency I would suggest you go ahead and create the extra routing file for your app as it might save you some trouble if your app gets more complex.

Keep in mind: Only call RouterModule.forRoot in the root AppRoutingModule (or the AppModule if that’s where you register top level application routes). In any other module, you must call the RouterModule.forChild method to register additional routes.

Step 5: Import your Secondary module in your Primary module (app.module.ts)

This is pretty much it! Once again this guide does not dive too deep in routing but rather how you could separate your modules and routing if your app needs to scale.

As I mentioned above this article was written to facilitate my learning and hopefully help some other people too. Any comments or constructive criticism is welcome!

--

--