5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Angularのページ遷移時に現在のURLのPathを取得する

Last updated at Posted at 2020-09-02

ユースケース

ログイン画面やサインアップ画面ではヘッダーを非表示にしたい。

ログイン画面(/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

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?