0

Currently, I am dealing with an angular project, I need to trigger an event on routing change/URL change from one page to another page (as it is an angular project page wont be refreshed).

I have tried with different scenarios in index.html page like below:

  window.onbeforeunload = function () {
   //not fit;
  });

    window.onhashchange = function () {
    //not fit;
   });

Can we have any other solutions to trigger an event on url change (I don't want to use listeners in angular).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

You can do this by implementing hashchange even on window

And if you are using jQuery, this plugin might help you.

Or in your case check pure JS code

function hashHandler() {
    this.oldHash = window.location.hash;
    this.Check;

    var that = this;
    var detect = function() {
        if(that.oldHash != window.location.hash) {
            alert("HASH CHANGED - new has" + window.location.hash);
            that.oldHash = window.location.hash;
        }
    };

    this.Check = setInterval(function() { detect() }, 100);
}

var hashDetection = new hashHandler();

Pure demo code example for angular with router:

import { Component, OnInit } from '@angular/core'; // I import Location so that I can query the current path
import { Location } from '@angular/common'; // I also import Router so that I can subscribe to events
import { Router } from '@angular/router'; 

@Component(
{ selector: 'app-top-nav', 
  templateUrl: './top-nav.component.html', 
  styleUrls: ['./top-nav.component.scss'] }
)
export class TopNavComponent implements OnInit { 
    route: string; 

    constructor(location: Location, router: Router) { // within our  constructor we can define our subscription
       // and then decide what to do when this event is triggered.
       // in this case I simply update my route string.
       router.events.subscribe((val) => { if(location.path() != '') { this.route = location.path(); } else { this.route = 'Home' } }); 
    } 

    ngOnInit() { 
    } 
} 

The above code should work.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
hotheadhacker
  • 182
  • 10