How to *ngIf on router link?

2020-05-21 09:03发布

问题:

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']"

回答1:

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>


回答2:

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 === '/';
  }
}


标签: angular