简体   繁体   中英

How to use Angular 9 navigation bar with router-outlet outside the app.component

I'm a beginner in angular.I have created a navigation bar and this is my code inside the app.component

<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div>
       <a routerLink="/login">Login</a>
       <a routerLink="/register">Register</a>
    </div>
  </div>
</nav>
<div>
  <router-outlet></router-outlet>
</div>

This works fine as follows Routing to logging component when logging is clicked

Routing to register component when register is clicked

But when I select another component in my route the navigation bar still exists.So I need my nav bar with logging and register only in my Home component.It should not exist when I routes the other components.I think if i write my code inside another component except the app.component it will work.But how can I use router-outlet and everything on another component.Please help with example. How can I implement that?

in app.component.html add to

<nav *ngIf="isHomePage" class="navbar navbar-default"></nav>

in app.component.ts -> ngOnInit()

this.router.events.subscribe(e => {
 if (e instanceof RouterEvent) {
   this.isHomePage = e.url.split('/').includes('home');
  }
});

Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM