Same Angular Route for Different Components
In this article, I will share a technique I used in order to serve two different components utilizing the same route path.
First, let’s discuss why you would want that.
Use Cases
- You have different implementations of a specific component controlled by some configuration or logic. This is the situation I was facing.
- Different users have different access levels and you want to use the same route for every user but while doing so, provide a different experience for each user profile.
- AB testing — Comparing two versions of a component/page and collecting metrics before deciding which one to use.
The Problem
One day, we decided to redesign our homepage from scratch. When the new homepage was almost finished, we were facing a dilemma over what’s the best way to open this new homepage for those who had the feature-toggle, and keep showing our old homepage for everyone else.
Keep in mind that this homepage route is loaded straight from the app-routing.module, it’s not a component that is loaded by selector like
<app-home></app-home>
so no *ngIf
It was clear that we needed something like this:
The Missing Piece of the Puzzle
The missing intermediate component is just a logic-infused module.
Let’s follow the steps I went through to make this module work:
- First, create the new module. I called mine HomeHandlerModule. This is the step where all the magic happens ✨.
Notice the module’s providers array, it provides ROUTES, which is the DI Token for router configuration; useFactory points to the function with the logic for deciding who gets A and who gets B; deps array lists the dependency for that function or, in other words, its arguments.
2. app-routing.module.ts
Instead of this:
{
path: 'home',
loadChildren: () =>
import('./home/home.module').then((m) => m.HomeModule)
}
We now use our new smart module:
{
path: 'home',
loadChildren: () =>
import('./home2/home-handler.module').then((m) =>
m.HomeHandlerModule)
}
3. Create a new feature module home2.module.ts that loads when
the feature-toggle is on. This module will hold the new layout I want to introduce.
Conclusion
In the case of larger and more complex apps, using ngIf isn’t always the best solution. This Angular way is more efficient and maintainable, so use the right tools for the job.