0

For my Angular 9, app, I have a simple app layout

<app-navbar></app-navbar>
<router-outlet></router-outlet>

The navbar component looks like

<mat-toolbar color="primary">
  <mat-toolbar-row>
    <h1>My App</h1>
    <span class="menu-spacer"></span>
    <div>
      <a mat-button [routerLink]="'/'"> Home </a>
      <a mat-button [routerLink]="'/latest'"> Latest </a>
      <a mat-button [routerLink]="'/current'"> Items </a>
    </div>
  </mat-toolbar-row>
</mat-toolbar>

I'm trying to figure out what the Angular way is to change the link to be just text instead of an anchor if the user is already on that page. What is the proper way to suppress the link generation and just have text if the URL matches what I want to route to?

satish
  • 703
  • 5
  • 23
  • 52
  • Does this answer your question? [How to set Bootstrap navbar "active" class in Angular 2?](https://stackoverflow.com/questions/35422526/how-to-set-bootstrap-navbar-active-class-in-angular-2) – Ashish Dahiya Jan 25 '21 at 19:16
  • This is what you need https://angular.io/api/router/RouterLinkActive. Use routerLinkActive directive and your own css to make it look like plain text. – Ashish Dahiya Jan 25 '21 at 19:18
  • @Ashish, Per my understanding of "routerLinkActive", it applies to an existing anchor tag. I would prefer not to have an anchor tag and instead just have text if the current URL matches that of an anchor, otherwise, I would prefer to have the anchor. – satish Jan 25 '21 at 20:59
  • does this help you https://stackoverflow.com/a/65898470/8260767 – Ashish Dahiya Jan 27 '21 at 13:58

2 Answers2

0

You can check your current route by subscribing to the router events in your navbar

class NavbarComponent {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
        console.log(val) 
    });
  }
}

https://angular.io/api/router/RouterEvent

Perhaps ActivatedRoute is a better solution for you:

export class NavbarComponent {
  constructor(private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(
      params => console.log('queryParams', params));
  })
}
misha1109
  • 358
  • 2
  • 5
  • Yeah it could, Basically here the navbar will receive data about the router change, you can extract all kinds of information from what's emitted. – misha1109 Jan 26 '21 at 06:49
0

Try this, i think this is what you are trying to do. Use routerLinkActive to specify the custom css class anchor-to-text

<a mat-button [routerLink]="'/'" routerLinkActive="anchor-to-text"> Home </a>

in your navbar component css file write our own css to make the anchor tag look like plain text

.anchor-to-text {
    cursor:text;
    color:inherit;
    text-decoration:none;
    pointer-events:none;
}
Ashish Dahiya
  • 650
  • 5
  • 14