【问题标题】:Hide Header Component on certain route (Angular 5)在某些路线上隐藏标题组件(Angular 5)
【发布时间】:2018-07-29 07:50:07
【问题描述】:

我想在某些路线上隐藏一个标题

当您在家时,路线旁边没有任何东西,所以www.mywebsite.com 但是当您登录时,路线中总会有app,所以从现在开始的每个页面都会像这样www.mywebsite.com/app/whatever基本上我当路由中有app 时,想隐藏我的标题

我试过这样做..但它似乎没有工作

任何帮助将不胜感激,如果您知道更好的方法,请告诉我!

component.html

<home-header *ngIf="router != '/app'"></home-header>

component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';


export class RootComponent {
     router: string;

     constructor(
        private _router: Router
     ) {
         this.router = _router.url;
     }
}

编辑

我已经尝试过这样做..

<home-header *ngIf="router.indexOf('app') > -1"></home-header>

那没用

我也尝试过这样做..

 export class RootComponent {
    router: string;

    constructor(
        private _router: Router
    ) {
        this._router.events.subscribe(() => this.router = this._router.url );
      }
 }

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    我从http://stackoverflow.com/a/41684866/4194436 找到了解决方案

    在您的 component.ts

    import { Router } from '@angular/router'
    
    //...
    
    constructor(
       public router: Router
    ) 
    

    然后在你的 component.html

    <home-header *ngIf="!router.url.includes('app')"></home-header>
    

    所以基本上如果路由 url 不包含 'app' 则显示home-header 组件。

    所以基本上如果路线不包括app,则显示home-header

    【讨论】:

    • 它在 IE 上不起作用,因为不支持包含。并且使用 indexOf 解决方案,我在 VS 代码中得到“预期操作符具有相似类型或任何类型”错误
    • 你可以使用 polyfill stackoverflow.com/questions/31221341/…
    【解决方案2】:

    您只设置了一次路由器变量,您应该为变量更改添加订阅:

    constructor(private _router: Router) {
       // this.router = _router.url;
       this._router.events.subscribe(()=> this.router = this._router.url );
    }
    

    您可以在here找到更多相关信息。

    不要忘记取消订阅组件销毁以避免内存泄漏。

    【讨论】:

    • 您能否为您的问题制作一个堆栈闪电战?
    • 我找到了答案,&lt;home-header *ngIf="!_router.url.includes('app')"&gt;&lt;/home-header&gt;
    【解决方案3】:

    试试:

    *ngIf="router.indexOf('app') > -1"
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 2021-11-26
      • 1970-01-01
      • 2014-07-04
      • 1970-01-01
      相关资源
      最近更新 更多