Home > OS >  create one navbar and use it on different pages with different style
create one navbar and use it on different pages with different style

Time:02-06

can I create one navbar and use it on different pages with different style in angular ? On the first page the دnavbar is transparent and appears after scrolling. But I want it to be white and sticky in the rest of the other pages

CodePudding user response:

You can check url and add different navigation components based on current route.

constructor(private router: Router ) {
   console.log(this.router.url); //route name
}

CodePudding user response:

If you have a navbar in the main component, then you can update its sticky behavior with 2 approaches:

Approach 1 (Preferred way):

Let's say that you already have many pages where you want your navbar to be sticky or transparent. Going to each page & changing some configs is time-consuming.

Instead, you subscribe to Router's NavigationEnd event in app.component.ts

 constructor(private router: Router) {}

  setNavSticky=true; //Default to true if we have many pages

  ngOnInit() {
    this.router.events.pipe(
      filter(ev=>ev instanceof NavigationEnd)
    ).subscribe((navEndEvent:NavigationEnd)=>{
      if(navEndEvent.url.includes('/home')){
        //Add more pages in condition for which navbar should not be sticky
        this.setNavSticky=false;
      }
      else{
        this.setNavSticky=true;
      }
      
    })
  }

Bind the sticky class in the app.component's HTML:

<nav  [class.sticky]="setNavSticky">
  <header>My main navbar</header>
  ...
</nav>

Approach 2: Create a utility service at the root level which has the property isNavbarSticky. All the pages that want to set it false, can do so by injecting it in their component file.

With approach 2, you have to manually set/unset isNavbarSticky in pages that don't want sticky navbar.

  •  Tags:  
  • Related