ユースケース
ログイン画面やサインアップ画面ではヘッダーを非表示にしたい。
ログイン画面(/login
)、サインアップ画面(/signup
)ではヘッダーを非表示にするために表示しているページのパスを取得し、事前に定義したパスにマッチしているかをチェックする。
例えば、
http://localhost:4200/login
→ヘッダー非表示
http://localhost:4200/menu
→ヘッダー表示
Routerを使うのが今のところ最適解っぽい
ActivatedRouterのsnapShotを使うなどいくつかの方法がありますが、この方法がシンプルかと思います。
テンプレート
<app-header *ngif="!hidden"></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
TypeScript
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
hiddenPath: string[] = ['login', 'signup'];
hidden: boolean;
constructor(
public router: Router,
) { }
ngOnInit() {
this.router.events.pipe(
filter(f => f instanceof NavigationEnd)
)
.subscribe((s: any) => {
this.hidden = this.hiddenPath.some(e => s.url.includes(e));
});
}
}
参考URL
Angular 日本語ドキュメンテーション - NavigationEnd
[Angular] router-outletの外で現在のurlを取得 | COTeggのバケツ
JavaScriptのsomeとeveryがすごく便利 - Qiita