Monitoring URL changes in Angular2 using the HostListener

I have a common navbar component that is included in every page of my website.
I would like it to detect when the URL changes using a HostListener.

@HostListener('window:hashchange', ['$event'])
onHashChange(event) {
    this.checkCurrentURL();
}  

private checkCurrentURL(){
    console.log("location: "+window.location.pathname)
}

Unfortunately, the current implementation does not seem to be working. Any suggestions?

EDIT: SOLUTION

I have discovered a solution that does not involve HostListener, but it is effective.

constructor(private router : Router){
 router.events.subscribe((val) => {
  this.checkCurrentURL();
 });
}

Answer №1

There's no need for a HostListener in this scenario. If you're working on a single page application, it's best to subscribe to the route change event.

Answer №2

In an Angular Single Page Application, you have the ability to create a global variable window within a component. By utilizing this window global variable, you can effectively monitor and track each and every route that your application takes.

window.location.href

The window.location.href property allows you to retrieve the current URL, enabling you to detect any changes in the URL.

constructor(private router : Router){
 router.events.subscribe((val) => {
    console.log(window.location.href); 
 });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript: Defining function overloads with a choice of either a string or a custom object as argument

I'm attempting to implement function overloading in TypeScript. Below is the code snippet I have: /** * Returns a 400 Bad Request error. * * @returns A response with the 400 status code and a message. */ export function badRequest(): TypedRespons ...

Is it possible to load a script conditionally in Angular 2 using the Angular CLI

Is it possible to conditionally load scripts using Angular CLI? I am looking to dynamically load a script in this file based on the environment or a variable. For example, I want to load a specific script in production but not in development. How can I ac ...

Deactivate the react/jsx-no-bind warning about not using arrow functions in JSX props

When working with TypeScript in *.tsx files, I keep encountering the following error message: warning JSX props should not use arrow functions react/jsx-no-bind What can I do to resolve this issue? I attempted to add configurations in tslint.json js ...

ERROR : The value was modified after it had already been checked for changes

Encountering an issue with [height] on the main component and seeking a solution Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '753'. Current value: '731'. I have th ...

I am looking to generate an array with key-value pairs from an object that will be seen in the examination

I have a task that involves configuring a table and creating objects with key-value pairs for each key. type KeyValuePair<T> = {/** ... */}; let userKeyValuePair :KeyValuePair<{id:number,userName:string}>; // => {key:'id',value: ...

The function onClick in Chart.js allows for passing the selected object in Typescript

In the documentation for Chart.js, I found a reference to an onClick function that is triggered whenever a click event occurs on the chart. The code snippet provided looks like this: options: { onClick: this.Function } Function(event, array){ ... } ...

Use Advanced Encryption Standard Algorithm (AES) to encrypt text with TypeScript and decrypt it using C# for enhanced security measures

Struggling with implementing encryption in TypeScript and decryption in C#. After searching online, I found some resources related to JavaScript, not TypeScript. Encrypt in JavaScript and decrypt in C# with AES algorithm Encrypt text using CryptoJS libra ...

What steps should I take to resolve the missing properties error stating '`ReactElement<any, any>` is lacking `isOpen` and `toggle` properties that are required by type `SidebarInterface`?

I've encountered an issue with two React components that appear to be configured similarly. The first component is a Navbar: type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> & { ...

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

How To Retrieve the Index of a Specific Row and Column in AgGrid (Angular)

Right now, I can retrieve the row data using the gridApi but I am struggling to determine the column index of the selected row. The method this.gridApi.getSelectedRows() does not provide any information about the column index. I would greatly appreciate ...

Ensure that the input field consistently shows numbers with exactly two decimal places

Below is an input field that I want to always display the input value with 2 decimal places. For example, if I input 1, it should show as 1.00 in the input field. How can this be achieved using formControl since ngModel is not being used? Thank you. I att ...

An error has occurred while attempting to differentiate '[object Object]'. In Angular, only arrays and iterables are permitted for this operation

Can someone help me with resolving the error I am encountering while trying to display data on the front end? service.ts rec_source(){ var headers = new HttpHeaders().set('Authorization', 'Token ' + localStorage.getItem('u ...

The TypeScript error is causing issues in the Express router file

Here is the structure of my module: import * as express from 'express'; let router = express.Router(); router.post('/foo', function(req,res,next){ // ... }); export = router; However, I'm encountering the following error: ...

How to dynamically adjust column width based on maximum content length across multiple rows in CSS and Angular

I am attempting to ensure that the width of the label column in a horizontal form is consistent across all rows of the form based on the size of the largest label. Please refer to the following image for clarification: Screenshot Example All label column ...

How can I test for equality with an array item using v-if in Vue.js?

Currently, I am facing a challenge in my Vue.js project where I need to determine if a number is equal to an element within an array. Here is the code snippet that I am working with: <div v-if="someValue != arrayElement"> // </div> I am st ...

Best Practices for Error Handling in Typescript

After delving into articles about error handling, a thought lingers in my mind - is throwing an exception on validation logic in the value object really the most efficient approach? Take for example this class that represents a value object: export class U ...

What is the best way to specify a function parameter as the `QUnit` type using TypeScript in conjunction with QUnit?

In my project, which is partially written in TypeScript and licensed under MIT, I am utilizing QUnit. I have some TypeScript functions that require QUnit as a parameter, and I would like to define their types based on its interface from the typings. For e ...

Asserting types for promises with more than one possible return value

Struggling with type assertions when dealing with multiple promise return types? Check out this simplified code snippet: interface SimpleResponseType { key1: string }; interface SimpleResponseType2 { property1: string property2: number }; inter ...

Updating an Angular 4 component based on the current URL or the state of another component

https://i.sstatic.net/a7Ncu.png The main objective The primary goal here is to click on one of the top users displayed on the left and have the details about that user refreshed on the right side. This requires establishing a communication link between t ...

Tips for adjusting the material ui Popper width to fit the container without disabling the portal

Currently utilizing the material-ui popper library. I am trying to allow the popper to extend outside of its container in the vertical direction. To achieve this, I have set disableportal={false}. However, upon setting disableportal to false, when assign ...