Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29149

Need to have different buttons in my header based on the route

This one is not very complex but I just don't know the way to do this in angular.

So, let say I have the following routes in my app

/
/bar
/foo

In my header I always have one button, based on the active route it is a hamburger or a back button; if I'm on the "/" route I need the hamburger button and for all other routes the back button

<header>
   <button *ngIf="!isRoot">Back</button>
   <button *ngIf="isRoot">Hamburger</button>
</header>

 <router-outlet></router-outlet>

With the following code in my AppComponent

 this.router.events
  .subscribe(
    (event: NavigationEvent) => {
      if (event instanceof ActivationStart) {
        this.isRoot = !!event.snapshot.url[0]?.path; // is empty string for /
      }
    });

This works great if I navigate in my app, but it doesn't if I hit reload, because that is not a route change and the code above is not triggered. Now before I start with window.location I was wondering if there is still something I can do with ActivatedRoute. Any suggestions?

Upvotes: 0

Views: 554

Answers (1)

ulmas
ulmas

Reputation: 2253

For the initial load, instead of relying on the NavigationEvent, you can use the this.router.url, something like:

this.isRoot = this.router.url === '/';

Upvotes: 1

Related Questions