简体   繁体   中英

Display element based on route - Angular

I'm having awful trouble trying to make the navbar set display:none based on the route I want. I did succeed in subscribing to the route, but I can't relate it's display based on it.

so far I have this:

export class AppComponent implements OnInit {

  jwtHelper: JwtHelper = new JwtHelper();
  public location = '';

  constructor(private authService: AuthService, private router: Router, private http: Http) {
    this.location = router.url;
    this.router.events.subscribe((location) => {
      console.log(location);
      return true;
    });
  }
}

For my app component.ts

<div class="app-nav">
  <!-- style="display:none; -->
  <app-navbar></app-navbar>
</div>
<div class="container outlet">

  <router-outlet></router-outlet>

</div>

and html

the <app-nav></app-nav> selector must not appear only when the URL is empty, which is the '/' route, but must be available in every other route. Can someone help me?

So you could basically leverage the power of rxjs here. this.router.events is a stream of events (known as Observable). We can take the stream and convert it ( map ) to a boolean property. Then we set an *ngIf on a component that we want to toggle, as follows:

<app-nav *ngIf="showNav$ | async"></app-nav>

Since this.router.events is a stream, every time it emits a new value, a new boolean will be generated. The stream used in the html template used together with the async pipe, unwraps the boolean value into the html, it also automatically subscribes and unsubscribes for you.

A full working stackblitz is here .

PS. And by the way, do not get discouraged by someone downvoting your questions, it happens more and more often here, without explanation why. I upvoted your question back, because it makes a perfect sense and answers can be helpful to others.

Conditional Rendering

<Component *ngIf="iWant ? true : false" />

It looks something like this.

check this docs

You can simply do this:

<h2 *ngIf="route.url === '/'"> {{title}} </h2>

or

<h2 *ngIf="route.url !== '/'"> {{title}} </h2>

or

<h2 *ngIf="route.url === '/books'"> {{title}} </h2>

In the component inject the object Router in the constructor

  constructor (public route: Router) {}

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