如何仅在特定路线上显示元素?

时间:2019-06-23 15:04:24

标签: angular

我有一个带有一些基本登录和注册路由的导航栏,但问题是,在主页('/')上有一个关于我们部分,我不想在登录时显示该部分('/ login')或signup('/ signup')页面。那么,如何仅在route('/')上显示该部分?

2 个答案:

答案 0 :(得分:2)

您可以将路由器events与已解析的urlAfterRedirects结合使用,并放置在事件对象中:

export class NavComponent {
  readonly showAbout$ = this.router.events.pipe(
    filter((event) => event instanceOf NavigationEnd)
    map((event) => this.canShowAbout(event.urlAfterRedirects)),
    startWith(this.canShowAbout(this.router.url))
  )

  constructor(readonly router: Router) {}

  canShowAbout(url: string): boolean {
    return ['/login', '/signup'].every((path) => !url.startsWith(path)
  }
}

,然后在您的组件中使用async管道:

<nav>
  <a routerLink="/home">Home</a>
  <a *ngIf="showAbout$ | async" routerLink="/about">
    About
  </a>
</nav>

答案 1 :(得分:1)

.ts文件中

export class Page {
  __URL:string = ""
  constructor(router: Router) {
   console.log(router.url); // This will print the current url
   this.__URL = this.router.url;
  }
}

.html文件中,您可以使用*ngIf

<div *ngIf="__URL === '/'">
 // Render whatever you want
</div>

#Edit

尝试用Location代替Router

import { Location } from '@angular/common';

export class AppComponent implements OnInit {
  constructor(private location: Location) {}

  ngOnInit(){
    console.log(this.location.path());
  }

}

随时查看docs

如果它不起作用,请尝试以下

 this.router.events
  .pipe(
    filter(e => e instanceof NavigationEnd)
  )
  .subscribe( (navEnd:NavigationEnd) => {
    console.log(navEnd.urlAfterRedirects);
  });