4

I need to identify when an anchor is changed and so call a function

Where I set the fragment:

  changeFragment(id) {
    this.router.navigate([], { fragment: id });
  }

Any help is welcome, thanks

Huangism
  • 16,278
  • 7
  • 48
  • 74
user3140824
  • 338
  • 5
  • 25

1 Answers1

6

Inject ActivatedRoute service in construtor, Then use fragement method in Activatedroute to listen fragement changes

Try this:

 this.route.fragment.subscribe( fragment =>{
      console.log(fragment);
 })
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
  • 1
    Somehow this did not work consistently for me. It would fire once on each fragment change but not again e.g. if my SPA app has 2 pages, one at /home and the other at /report, and i land at /home then on navigating to /report the first time this observable would fire but never again if i navigate away from /report and then come back. I ended up using `router.events.subscribe` as suggested in https://stackoverflow.com/questions/33520043/how-to-detect-a-route-change-in-angular. – oomer May 25 '22 at 11:01
  • Are you using fragment in your routes? – Chellappan வ May 25 '22 at 11:38
  • yes, why do you ask ? – oomer May 28 '22 at 18:20