0

I'm new to Angular and I need some advice

I'm using a bootstrap navbar (ul and li elements) in a header component and a router outlet.

<app-header></app-header>
<router-outlet></router-outlet>

I want to hide and show certain navbar items based on the component that is currently showing. What is the best practice to achieve this?

Daniel Gretzke
  • 426
  • 4
  • 19

4 Answers4

2

Maybe not best practice as I just came up with it but here is my try:
You can inject the Router in your AppHeaderComponent and do something like this:

export class AppHeaderComponent {
    currentRoute$: Observable<string>;
    showPostsNavbarItems$: Observable<boolean>;
    constructor(private activatedRoute: ActivatedRoute) {


        this.currentRoute$ = router.events.pipe(
            filter(event => event instanceof NavigationEnd),
            pluck('urlAfterRedirects')
        );
        this.showPostsNavbarItems$ = this.currentRoute$.pipe(
            map(route => route === 'whatever')
        );
    }
}

So you can use the *ngIf + async pipe in your template to show/hide them.

I am not sure how the url in event.urlAfiterRedirects looks like though, I haven't tried it yet.

I hope I could help :)

SirDieter
  • 309
  • 2
  • 9
1

You can try with this solution.

I have create a demo on Stackblitz

<div class="container">
<app-side-nav *ngIf="blankUrl || !isCheckoutRoute()"></app-side-nav>

<div id="main">
  <router-outlet></router-outlet>

</div>

</div>
Krishna Rathore
  • 9,389
  • 5
  • 24
  • 48
1

There are two ways to do so.

  1. Make it condition based. Show it when you want it using *ngIf.

Please see this answer for more - Answer.

  1. The second and the best ways is to handle this with the modules.

Make a different module which does not include navbar and put the components which not require navbar. And rest of the components in the module which requires navbar.

Surjeet Bhadauriya
  • 6,755
  • 3
  • 34
  • 52
1

If the items is dynamic flow this You can create a global service has an public poperty with type of array , and render this array of item on navbar

second step in each componet inject the global service and at ngOninit method assaing new item to the service , so every time navbar will have current component items.

if the items is already render in navbar just create a global service with property of string , this property like flag, at ngOninit method assign component flag value like this 'home','admin','setting'

<ul>
<li *ngIf="globalService.selectdFlag === 'home'">home 01</li>
<li *ngIf="globalService.selectdFlag === 'home'">home 02</li>
<li *ngIf="globalService.selectdFlag === 'admin'">admin 01</li>
<li *ngIf="globalService.selectdFlag === 'admin'">steeing 01</li>
<li *ngIf="globalService.selectdFlag === 'setting'">setting 01</li>
</ul>

Happy Coding

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91