How to configure Complex or Dynamic Routing in Angular Application

Routing is a very powerful concept in Angular and the @angular/router library package enables navigation from one component to another as the user performs application tasks.

We define routes in AppRoutingModule in Angular with a related component like below 

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FirstComponent } from './components/first/first.component';
import { SecondComponent } from './components/second/second.component';

const routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
];

@NgModule({
imports: [RouterModule.forRoot(routes, {
initialNavigation: 'enabled'
})],
exports: [RouterModule]
})
export class AppRoutingModule { }


In the above example, if the route path "first-component" is hit then FirstComponent Component will be loaded in the browser similarly route path "second-component" is hit then SecondComponent will be loaded in the browser.

In some cases, we require dynamic routing in Angular and it's not possible to mention every route in the Route array of AppRoutingModule.

Today we are going to look at how can we configure dynamic routing in the Angular

app-routing.module.ts file

export const AppRoutes: Routes = [
{
path: 'article/:id',
component: ArticleComponent,
children: [
{
path: '',
component: ArticleComponent
},
{
matcher: ComplexUrlMatcher("title", /[a-zA-Z0-9]+/),
component: ArticleComponent
},
]
}
];


complex.url.matcher.ts

import { UrlSegment, UrlSegmentGroup, Route } from '@angular/router';

export function ComplexUrlMatcher(paramName: string, regex: RegExp) {
return function (
segments: UrlSegment[],
segmentGroup: UrlSegmentGroup,
route: Route) {
const parts = [regex];
const posParams: { [key: string]: UrlSegment } = {};
const consumed: UrlSegment[] = [];

let currentIndex = 0;

for (let i = 0; i < parts.length; ++i) {
if (currentIndex >= segments.length) {
return null;
}
const current = segments[currentIndex];

const part = parts[i];
if (!part.test(current.path)) {
return null;
}

posParams[paramName] = current;
consumed.push(current);
currentIndex++;
}

if (route.pathMatch === 'full' &&
(segmentGroup.hasChildren() || currentIndex < segments.length)) {
return null;
}

return { consumed, posParams };
}
}


In the above route configuration whenever we hit the browser article/id/"anything-in-route"  it will load ArticleComponent in the browser.

Please note id can be any number or identifier through which you can load the data from the backend.

In ArticleComponent you can get the id and title on ngOnit method as below.

ngOnInit(): void {
this.router.params.subscribe(routeParams => {
this.artcleTitle = this.capitalizeFirstLetter(this.location.path().split("/")[3].replace(/-/g, ' '));
this.getArticle(routeParams.id);
});
}


Hope you have enjoyed the article.

Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee