Subscribing to URL fragment not firing event on change in Angular

447 Views Asked by At

I am using Angular 13 and I am trying to subscribe to the ActivatedRoute 'fragment'. The subscription is only receiving a notification when the page first loads, but is not receiving updates when the fragment gets updated.

Here is an example of what I am doing:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
    selector: 'app-my-component',
    templateUrl: './my-component.component.html'
})
export class MyComponentComponent implements OnInit {
    constructor(private activatedRoute: ActivatedRoute) { }

    ngOnInit(): void {
        this.activatedRoute.fragment.subscribe((fragment: string) => {
            console.log("test page: ", fragment)
        });
    }
}

I would expect that on page load, and every time the fragment changes I would receive a notification to this subscription.

What I am actually experiencing is that this subscription is only notified on the initial page load, and not on any subsequent changes.

1

There are 1 best solutions below

1
On

you need to subscribe to the router events:

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

@Component({
  templateUrl: './my-component.component.html',
  styleUrls: [
    './my-component.component.scss'
  ]
})
export class MyComponent implements OnInit, OnDestroy
{
  private routerSubscription:Subscription;
  
  public constructor(
    private router:Router
  ){}

  public ngOnInit(): void
  {
    this.routerSubscription = this.router.events.subscribe(event => {

        if(event instanceof NavigationEnd)
          console.log( event.url); // do something here...
    });

  }
  
  public ngOnDestroy():void
  {
    this.routerSubscription?.unsubscribe();
  }
}