routerLink change in Angular 16 – Angular

by
Ali Hasan
angular angular-routing angular16

The Problem:

In an angular version < 16, relative links worked in the routerLink property. However, after updating to angular 16, the links generated by routerLink have a different format. For example, a relative link like routerLink="contributors" generated a link like /security/(readers//left-menu:contributors) in angular 16, which is not the desired behavior. The goal is to maintain the same behavior as before, where relative links worked correctly.

The Solutions:

Solution 1: Angular 16 RouterLink Change

With the Angular 16 update, the format of router links has changed. To maintain the same behavior as before, absolute links should be used instead of relative links. The issue arises when using relative routes, as explained in the GitHub issue linked in the response. This warning was already present in Angular 15.x, but the navigation still worked.

Solution 2: Importing RouterModule

To resolve the issue, import the RouterModule in your Standalone Component where you face problems with relative routes or routerLink bindings. Importing RouterModule adds the necessary properties and functionalities to the component, enabling it to work with relative routes and bindings effectively.

Here’s an example of how to import RouterModule in your Standalone Component:

import { Component, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { RouterModule } from '@angular/router';

@Component({
  selector: 'my-selector',
  standalone: true,
  imports: [CommonModule, MatButtonModule, RouterModule],
  templateUrl: './project-overview.component.html',
  styleUrls: ['./project-overview.component.scss'],
})
export class ProjectOverviewComponent {}

In this example, we import the RouterModule along with other necessary modules like CommonModule and MatButtonModule. By importing RouterModule, you can utilize features like relative routes and routerLink bindings within your template.

Q&A

Any idea why routerLink now have a different format in Angular 16?

It’s linked to this issue: https://github.com/angular/angular/issues/50611

What can be the workaround for routerLink issue in Angular 16?

Avoid using relative links and stick with absolute ones.

How to get relative routes working in Angular 16?

Try: [routerLink]="[‘..’, ‘project-creator’]" and import RouterModule in your Standalone Component.

Video Explanation:

The following video, titled "Related Video", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

This video provides further insights and detailed explanations related to the content discussed in the article.