隐藏指定路线上的标头 - 角度 6

Ric*_*des 3 typescript angular angular6

我试图隐藏标题,仅在一条路线中。

假设我有 3 条路线route1route2route3

我有一个名为 的组件app-header

app-header我希望当用户输入时隐藏该组件route1,并在其他 2 个路由中显示该组件。

我在 stackoverflow 上找到了一些主题,但没有一个对我有帮助=/

你们能给我一些帮助吗?

这是我的代码:

  • 应用程序组件.ts

    export class AppComponent implements OnInit {
        showHeader = true;
    
        constructor(
            private router: Router
        ) {
            this.router.events.subscribe(event => this.modifyHeader(event));
        }
    
        ngOnInit() {
        }
    
        modifyHeader(location) { // This method is called many times
            console.log(location.url); // This prints a loot of routes on console
            if (location.url === '/route1') {
                this.showHeader = false;
            } else {
                this.showHeader = true;
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

我正在使用角度6.1.4

小智 6

由于您知道要检测哪条路由,并且似乎在应用程序组件中有一个解决方案,因此我建议过滤路由器事件,如下所示:

export class AppComponent implements OnInit {
    showHeader = true;

    constructor(
        private router: Router
    ) {
        this.router.events.pipe(
            filter(e => e instanceOf NavigationEnd)
        ).subscribe(event => this.modifyHeader(event));
    }

    ngOnInit() {
    }

    modifyHeader(location) { // This method is called many times
        console.log(location.url); // This prints a loot of routes on console
        if (location.url === '/route1') {
            this.showHeader = false;
        } else {
            this.showHeader = true;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)