RouterModule.forRoot versus RouterModule.forChild

There are two methods we can invoke using RouterModule in order to register routes.

In case we declare the top-level routes of our application, we need to use RouterModule.forRoot. This method will register the top-level routes and return the routing module that should be imported by the root module of the application.

If we want to define routes in a lazy-loaded module and import the module returned by the invocation of the forRoot method, we'll get a runtime error. This is because the forRoot method will return a module with providers, which should be imported only once, by the top-level module. In order to register nested routes in a lazy-loaded module, we will need to use the forChild ...

Get Switching to Angular - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.