notebook

都内でWEB系エンジニアやってます。

Angularでページ遷移後に処理をする[NavigationEnd]

angularのrouterで取得できるイベントにNavigationEndというものがあるようです

ページ遷移後のイベントを扱うことができるようなので使ってみます

  • app.component.ts
import {Router,NavigationEnd} from "@angular/router";

constructor(
  private _router: Router
){
  this._router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
      console.log(event);
      // 何かしら処理
    }
  })
}
  • app.component.html
<nav.....
.....
</nav>

<div style="float: right;">
  現在のパス: {{path}}
</div>

f:id:swfz:20170522033955p:plain

f:id:swfz:20170522034000p:plain

とすることでページ遷移完了後に何か処理を挟むことができます

遷移が終わるまで処理させたくない時や毎度ページが変わった時にさせたい処理がある場合に使えそうですね

フロント用のユーザーの行動ログ解析用の処理だったり、パンくず、メニュー関連の処理だったりを入れるのが良さそうに感じました

angularのAPIドキュメント眺めてると色々発見があって面白いですね