0
votes

We've got AccountComponent that contains some child links. We want to hide these child links whenever a child is active. Right now it seems we can achieve this in two ways:

routerLinkActive and checking isActive on each of them to hide with CSS:

<style>
  .content {
    &.child-active {
      .links {
        display: none;
      }
    }
  }
</style>

...

<div class="content" [class.child-active]="linkProfile?.isActive || linkSettings?.isActive">

  <div class="links">
    <a [routerLink]="['./profile']" routerLinkActive="active" #linkProfile="routerLinkActive">Profile</a>
    <a [routerLink]="['./settings']" routerLinkActive="active" #linkSettings="routerLinkActive">Settings</a>
  </div>

  <router-outlet></router-outlet>

</div>

Hardcoding current parent route and checking it's exactly active:

@Component({ ... })
export class AccountComponent {
  isParentActive$ = this.router.events
    .pipe(
      filter((event): event is NavigationEnd => event instanceof NavigationEnd),
      map(() => this.router.isActive('/account', true)),
    );
}

...

<div class="content">

  <div class="links" *ngIf="isParentActive$ | async === false">
    <a [routerLink]="['./profile']">Profile</a>
    <a [routerLink]="['./settings']">Settings</a>
  </div>

  <router-outlet></router-outlet>

</div>

The CSS way to me is quite hacky for obvious reasons and the Parent hardcoding an absolute route to check for exact equality can't be re-used when the path to it changes.

Is it possible to do this any better way or should an issue be created to improve the Router API within Angular?

1

1 Answers

0
votes

In documentation you have something like this:

<div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
  <a routerLink="/user/jim">Jim</a>
  <a routerLink="/user/bob">Bob</a>
</div>

This will set the active-link class on the div tag if the url is either '/user/jim' or '/user/bob'.

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

or you can try like this, if you want to remove it completely (need to test it not totally sure if it works)

<div ngIf="stuff.isActive" routerLinkActive="active-link" #stuff="routerLinkActive">
   <a routerLink="/user/jim">Jim</a>
   <a routerLink="/user/bob">Bob</a>
</div>

you can also try to simplify it (if there is no ChangeDetectionStrategy.OnPush):

<div *ngIf="router.isActive('/account', true))">...</div>