Using routerLinkActive in Angular 17

I'm re-writing an Angular app using Angular 17, which is a departure from the architecture of previous versions of Angular. If you found my page, than it's likely that you are trying to use routerLinkActive, and it's not working. 

In Angular, routerLinkActive allows you to apply one or more CSS classes to an element if the element matches a route. 

<a mat-button  routerLink="/Home" routerLinkActive="active" ><mat-icon>home</mat-icon> Home</a>

In this example, when Angular route is set to "/Home", the <a> element will essentially be <a class="active">

So in your CSS file, which is in the same folder as your component, you need to define a class rule that tells the browser how to style the element. 

In my case, my CSS file is top-nav.compenent.scss and I've added this rule:

.active{
  background-color: darken(orange,25%);
  border-radius:10px 10px 0 0;
  color:black;
}


However, this still isn't enough to make it work. 
If you look at the Angular documentation for routerLinkActive at https://angular.io/api/router/RouterLinkActive
you'll see that this functionality is exported from RouterModule






In previous versions of Angular, you'd need to add that import to the top level of your app. In Angular 17, they moved those imports to the component level. 

In my case, that's top-nav.component.ts

import { Component } from '@angular/core';
import {MatMenuModule} from '@angular/material/menu';
import {MatIconModule} from '@angular/material/icon';
import {MatToolbarModule} from '@angular/material/toolbar';
import { RouterLink } from '@angular/router';
import { RouterModule } from '@angular/router';


@Component({
  selector: 'app-top-nav',
  standalone: true,
  imports: [MatMenuModule, MatIconModule,MatToolbarModule,RouterLink,RouterModule],
  templateUrl: './top-nav.component.html',
  styleUrl: './top-nav.component.scss'
})
export class TopNavComponent {


}

You'll need to Import RouterModule, and add it to the imports array in your @Component object. 


Comments

Popular posts from this blog

Using GIT with Arduino

Programming Arduino with Regular Expressions

Organize your Arduino code with header and class files