首页 > 解决方案 > 隐藏特定路线Angular6上的搜索栏

问题描述

我想在路由是时在我的标题上显示一个输入,/home并在它是其他东西时隐藏它。这是我现在尝试过的,但它不能正常工作。

.html

<div *ngIf="searchBarVisible">
    <input class="form-control" placeholder="Search">
</div>

.ts

searchBarVisible: boolean = false
constructor(private router: Router) {
    router.events.forEach((event) => {
      if (event instanceof NavigationStart) {
        if (event['url'] == '/home') {
          this.searchBarVisible = true
        } else {
          this.searchBarVisible = false
        }
      }
    });
  }

哪个似乎是问题?感谢您的时间!

标签: htmlangular

解决方案


您可以检查router.url 如下:

isHome(): boolean {
    const check = this.router.url.indexOf('/home');
    if (check) {
        return true;
    }
    return false;
}

进而,

<div *ngIf="isHome()">
    <input class="form-control" placeholder="Search">
</div>

推荐阅读