angularangular-routingangular-routerangular-routerlink

How to get Angular router to ignore query string params?


I have an Angular 16 application with routing. I have some links in other places that will redirect to this application with a query string appended like this: http://my-app.com?redirect=other-app.com

When the query string is present, it cannot properly set the routerLinkActive class specified. This is due to [routerLinkActiveOptions]="{ exact: true }" being set, but I have to set this here on the home page or else it will be set as active for all other pages

<a routerLinkActive="active"
   routerLink="/"
   [routerLinkActiveOptions]="{ exact: true }"> Home </a>
<a routerLinkActive="active" routerLink="/about"> About </a>
const routes: Routes = [
  { path: '', component: HomeComponent, },
  { path: 'about', component: AboutComponent, pathMatch: 'full' },
  ...
  { path: '**', redirectTo: '' },
];

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

Is there a way to get the router to ignore query string params, or is there some other way to do this that I'm missing?

EDIT: I have since found out that it's possible to set queryParams: 'ignored' like this:

<a routerLinkActive="active"
   routerLink="/"
   [routerLinkActiveOptions]="{ exact: true, queryParams: 'ignored' }"> Home </a>

which seems like it should work, but it has no effect.


Solution

  • There might be a better way to do this, but here's what I ended up doing

    public isHomePage = false;
    
    constructor(private router: Router) {}
    
    ngOnInit(): void {
      this.router.events.subscribe((event) => {
        if (event instanceof NavigationEnd) {
          this.isHomePage = event.url === '/' || event.url.startsWith('/?');
        }
      });
    }
    
    <a routerLink="/" [class.active]="isHomePage ">Home</a>
    

    now the following URLs will highlight this route as expected:

    But any other route will not highlight this route.