Angular - Custom Route Matches


What is Custom Route Matches?

In Angular, the custom route matches allow you to define a "specific condition" under which certain routes are matched. This is useful while controlling the application navigation when the URLs are more complicated.

Creating Custom Route Matches

The router in Angular supports a powerful matching strategy that you can use to help users navigate various sections in your application. This matching strategy supports static routes, variable routes with parameters (i.e., /:parameter), wildcard routes (i.e., **), and so on. Also, you can build your own custom pattern matching for situations in which the URLs are more complicated.

In this chapter, we will build a custom route matcher using AngularUrlMatcher. In Angular, UrlMatcher is a "function" used to define custom URL-matching logic for routes.

Let's create a sample Angular application to perform the creation of the custom router matcher.

Creating a Sample Application

We will use the Angular CLI to create a new sample application named angular-custom-route. In addition to the application creation, we will create a dashboard component.

Note: Make sure the Angular CLI is installed;if not,see this.

Step 1: Create a new Angular project, angular-custom-route as follows:

ng new angular-custom-route

Once you enter or write the above command in your IDE's terminal or node.js command prompt, it will ask a few questions as follows:

  • ? Which stylesheet format would you like to use?, select CSS
  • Do you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)?, select N

After a few seconds, your new Angular project will be ready; you can see it in your code editor with the name angular-custom-route.

Step 2: From your IDE terminal navigate to your application directory as follows:

cd angular-custom-route

Step 3: Create a component with the name dashboard as follows:

ng generate component dashboard

Step 4: In your code editor open the dashboard.component.html file and replace the below HTML code:

<h3>Welcome to Dashboard</h3>
<p>Hello {{ dashboard }}!</p>

Step 5: In your code editor locate the app.component.html file, and replace the below code with:

<h3>Routing with Custom Matching</h3>
Navigate to <a routerLink="/@Dashboard">my dashboard</a>
<router-outlet></router-outlet>

Configure Routes for your Application

Next, you need to add routing capabilities to theapp.config.tsfile. As a part of this process, we will create a custom URL matcher that looks for a Twitter handle in the URL. This handle is identified by a preceding@symbol.

Step 1: In your IDE (code editor) open the app.config.ts file.

Step 2: Add the following import statements:

import { provideRouter, withComponentInputBinding } from '@angular/router';
import {routes} from './app.routes';

Step 3: In the given array, add the provideRouter(routes, withComponentInputBinding()) statement as follows:

import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes, withComponentInputBinding())]
};

Step 4: Now, open the app.routes.ts file and define the "custom route matcher" as follows:

import { Routes, UrlSegment } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';

export const routes: Routes = [
    {
        matcher: (url) =>{
            if(url.length === 1 && url[0].path.match(/^@[\w]+$/gm)){
                return {
				consumed: url, 
				posParams: {
				dashboard: new UrlSegment(url[0].path.slice(1), {})}};
            }
            else{
                return null;
            }
        },
        component: DashboardComponent
    }
];

As we know the custom matcher is a function which is performed the following tasks as follws:

  • Thematcherverifies that the array contains only "one" element.
  • The matcher uses a regular expression to ensure that the format of the "dashboard" is a match.
  • If there is a match found, the function returns the "entire URL", defining a dashboard route parameter as a substring of the path.
  • If there is no match found, the function returns null, and the router continues to "look for other routes" that match the URL.

Reading the Route Parameters

As we created a link in our app.component.html file to redirect to the dashboard component, now we will bind the route parameter with the Dashboard component.

Step 1: Open the dashboard.component.ts file in your code editor and create an Input matching the dashboard parameter.

Note: As we imported withComponentInputBinding in our provideRouter. It will allow the Router to bind information directly to the route components.

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [],
  templateUrl: './dashboard.component.html',
  styleUrl: './dashboard.component.css'
})
export class DashboardComponent {
  @Input() dashboard!: string;
}

Step 2: Now run your application to check your custom URL matcher as follows:

ng serve

The output is as follows: