angularrouterlinkrouterlinkactive

Angular RouterLink Issue


Object: I have a menu with a searchBarInput on InputValueChange

=> update the url by adding a key search with the input value

=> it work well but by doing that I destroyed the sidebar routerLinkActive system.

why ? and how to resolve it?

Html

<div class="sidebar">
  <ul>
    <li>
      <a routerLink="/home" routerLinkActive="active">Home</a>
    </li>
    <li>
      <a routerLink="/about" routerLinkActive="active">About</a>
    </li>
  </ul>
  <div class="search-bar">
    <input type="text" [(ngModel)]="searchQuery" (ngModelChange)="onSearchQueryChange()">
  </div>
</div>

Typescript

// sidebar.component.ts

import { Component } from '@angular/core';
import { QueryParamService } from './query-param.service';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent {
  searchQuery: string = '';

  constructor(private queryParamService: QueryParamService) {}

  onSearchQueryChange() {
    // Create a JSON object with the search query parameter
    const queryParams = { search: this.searchQuery };

    // Call the service to update the query parameters
    this.queryParamService.updateQueryParams(queryParams);
  }
}

Service

// query-param.service.ts

import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class QueryParamService {
  constructor(private router: Router, private route: ActivatedRoute) {}

  updateQueryParams(queryParams: { [key: string]: string | number }) {
    const currentQueryParams = { ...this.route.snapshot.queryParams };
    const updatedQueryParams = { ...currentQueryParams, ...queryParams };

    this.router.navigate([], {
      relativeTo: this.route,
      queryParams: updatedQueryParams,
      queryParamsHandling: 'merge',
    });
  }
}

the routerLink is not updating on link change

The components are switching


Solution

  • why?

    It's because your routes don't match anymore. When you append your search parameter to the url, the route no longer matches.

    and how to resolve it?

    The documentation goes over this: https://angular.io/guide/routing-with-urlmatcher and https://angular.io/api/router/RouterLinkActive

    Basically you need to set a routerLinkOptions property. A decent example can be found here: How RouterLink and RouterLinkActive work?.