LoginSignup
3
1

More than 3 years have passed since last update.

【Angular】現在開いているページのurlを取得する

Posted at

やりたいこと

・ヘッダーでurlに応じてCSSの変更をしたい
・ページを切り替えるたびにurlを取得したい

Routerでイベントを監視

import { NavigationEnd, Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { filter } from 'rxjs/operators';

export class HeaderComponent implements OnInit,OnDestroy {
  activeUrl:string;
  urlSubs:Subscription;
  constructor(private router:Router) { }

  async ngOnInit() {
    const navigationEndUrl = 
      await this.router.events
      .pipe(filter<NavigationEnd>(e => e instanceof NavigationEnd));
    this.urlSubs = navigationEndUrl.subscribe(active=>{
      this.activeUrl = active.url;
      console.log(this.activeUrl);
    });
  }

  ngOnDestroy(){
    if(this.urlSubs){
      this.urlSubs.unsubscribe();
  }
}

router.eventsをsubscribeするとurlについての情報が色々流れてくるのですが
いっぱい流れてくるので今回欲しい情報があるNavigationEndのイベントの時だけ取得するようfilterで絞り込みます

スクリーンショット 2020-11-27 10.08.48.png
urlが取れました

あとはクラスバインディングでurlを条件にしたら実現できました

   <li class="nav-item">
      <a 
         class="nav-link"
         [class.active]="activeUrl == '/user'"
         routerLink="/user">User
      </a>
   </li>  

ページを開いた時一回だけurlを取得したい時の例

    import { filter, first, map } from 'rxjs/operators';

    // 最初の一回だけurlを取得する
    const navigationEndUrl = 
    await this.router.events
    .pipe(filter<NavigationEnd>(e => e instanceof NavigationEnd))
    .pipe(first())
    .toPromise();
3
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
3
1