How to *ngIf on router link?

后端 未结 3 1271
小鲜肉
小鲜肉 2021-02-01 16:01

I need to show some content on certain page, in other pages it shouldn\'t be visible. How do I achieve it ? it doesn\'t work

*ngIf=\"[routerLink]=\"[\'/home\']\"<

相关标签:
3条回答
  • 2021-02-01 16:29

    If your routes are well defined you can try this:

    isTournamentRoute() {
        return this.router.url.includes("/tournament");
    }
    

    Which is piggybacking off the non accepted answer to add a bit more flexibility.

    0 讨论(0)
  • 2021-02-01 16:36

    I'm using the other approach.

    template:

    <div class="col-12 col-sm-12 col-md-12 col-lg-12">
       <app-header></app-header>
       <app-banner *ngIf="isHomeRoute()"></app-banner>
    </div>
    

    .ts file:

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.less']
    })
    
    export class AppComponent implements OnInit {
    
      constructor(private router: Router) {}
    
      ngOnInit() {}
    
      isHomeRoute() {
        return this.router.url === '/';
      }
    }
    
    0 讨论(0)
  • 2021-02-01 16:41

    You can inject Router from '@angular/router' and get the current route you're on.

    For example:

    // mycomponent.component.ts
    class MyComponent {
        constructor(public router: Router) {
    
        }
    }
    
    // mycomponent.component.html
    <div *ngIf="router.url === '/some/route'">
    
    </div>
    
    0 讨论(0)
提交回复
热议问题