Have you ever needed to render a component conditionally on the same route and found yourself resorting to convoluted solutions?
Creating a new container component solely to render components conditionally? Or perhaps using a route factory? Or maybe you even considered giving up and using two separate routes instead?
In a previous article about feature flags in Angular, I discussed how to activate a route when a feature flag is enabled. But what if you need to conditionally render a component based on a feature flag on the same route?
It turns out that with the new CanMatchFn, we can define the same route with different components multiple times. Let's explore an example where the team introduces a brand new LoginComponent
.
// feature-flag.guard.ts
export const featureFlagGuard = (feature: FeatureFlags): canMatchFn => {
return (route, segments) => {
const featureFlagService = inject(FeatureFlagService);
return featureFlagService.getFeature(feature);
};
};
// routes.ts
[
{
path: 'login',
canMatch: [featureFlagGuard('newLogin')],
loadComponent: () => import('..').then((c) => c.NewLoginComponent),
},
{
path: 'login',
loadComponent: () => import('..').then((c) => c.OldLoginComponent),
},
]
First, we need to create the featureFlagGuard
. This guard is a canMatch
guard that enables or continues on the next route. In the featureFlagGuard
, we call a service that retrieves all the feature flags from an API. Using the getFeature
method, we check if the specified feature, provided as an argument, is enabled in the service. If the feature is enabled, the method returns true
, thereby activating the route.
In the routes file, we define the same route twice. If the feature flag called newLogin
is enabled, it will display the NewLoginComponent
. If it doesn't match, Angular will proceed to the next route, which in this case is again the login
path. Since this is the default, we don't need the canMatch
guard and can simply load the OldLoginComponent
.
This approach eliminates the need to create another component to combine them or resort to hacky solutions. It’s straightforward to follow. Cheers!
Top comments (0)