如何*路由器链接上的ngIf?

Tom*_*ski 24 angular

我需要在某些页面上显示某些内容,在其他页面中它不应该是可见的.我该如何实现?它不起作用

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

tt9*_*tt9 26

您可以从'@ angular/router'注入路由器并获取您当前的路由.

例如:

// mycomponent.component.ts
class MyComponent {
    constructor(public router: Router) {

    }
}

// mycomponent.component.html
<div *ngIf="router.url === '/some/route'">

</div>
Run Code Online (Sandbox Code Playgroud)

  • 不建议。 (3认同)
  • 您正试图在模板视图中访问私有财产 (2认同)
  • @ tt9如果路由器链接包含ID怎么办?例如`/ link1 / link2 / {id}'` (2认同)

小智 13

我正在使用另一种方法。

模板:

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

.ts 文件:

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 === '/';
  }
}
Run Code Online (Sandbox Code Playgroud)


cyb*_*guy 5

如果您的路线定义良好,您可以尝试以下操作:

isTournamentRoute() {
    return this.router.url.includes("/tournament");
}
Run Code Online (Sandbox Code Playgroud)

这是利用不被接受的答案来增加更多的灵活性。