Angular not triggering event upon changing URL fragment subscription

I'm currently using Angular 13 and attempting to subscribe to the ActivatedRoute 'fragment'. However, I am facing an issue where the subscription only receives a notification when the page initially loads, and does not update when the fragment changes.

Below is an example of my implementation:

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)
        });
    }
}

My expectation was to receive notifications from this subscription on page load and every time the fragment changes. However, the actual behavior is that the subscription is only activated on the initial page load and does not respond to subsequent changes in the fragment.

Answer №1

To activate the router events, make sure to subscribe to them:

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); // perform the desired action here...
    });

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

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

Missing "this" after initialization? (typescript/node/express)

I am currently working on creating a basic http application using node-express. One issue I encountered is that when setting up routes, the constructor of the MyRouter class has access to this, but it seems to be lost within the getRoutes() function. cla ...

The Art of Validating Configurations Using io-ts

I have recently switched to using io-ts instead of runtypes in a fresh project. In terms of configuration validation, my approach involves creating an object that specifies the types for each part of the config; const configTypeMap = { jwtSecret: t.str ...

Navigating Routes with Router in Angular 7: A Step-by-Step Guide

Within my sidebar navigation component, the sidebar.component.html file is structured as follows: <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav"> <a class="navbar-brand" href="#page-top"> <span cl ...

Utilize @db.Decimal within the Prisma framework for the parameters "s", "e", and "d"

When I define the schema in Prisma like this: value Decimal? @db.Decimal(7, 4) Why do I always get this format when retrieving the value from the database: "value": { "s": 1, "e": 0, & ...

Troubleshooting AngularJS2 and npm in WebStorm and Chrome for Windows users

Having completed the official Hero tutorial for AngularJs2 using Visual Studio Code, I decided to switch my coding and debugging setup to WebStorm+Chrome on Windows 10. To achieve this transition, I took the following steps: Installed Chrome JetBrains ...

What is the purpose of specifying the data types of my method parameters while I am incorporating an interface?

For instance: interface Foo { someProperty: Number someMethod?: (str: string) => void } class Bar implements Foo { someProperty = 42 someMethod (str) { console.log(this.someProperty) } } The str argument in someMethod() is clearly a str ...

Bringing in the MVC model class for an ASP.NET Core MVC application paired with an Angular 2 application

Currently, I am developing a sample Angular 2 application alongside ASP.NET Core MVC. I am curious if it is feasible to import a model class (let's say product.cs) that has been created in the "Models" folder directly into the Angular 2 application i ...

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

Error: Angular encountered an undefined variable when attempting to import 'node_modules/bootstrap/scss/grid'

Having some trouble setting up Angular with SCSS and Bootstrap. When attempting to run ng serve, I encountered the following error: ./src/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: Undefined variable. ...

Efficiently utilizing ngrx by orchestrating various services and actions to achieve accurate mapping

Combining multiple effects into one is my current goal due to an issue with dispatching actions separately. The aim is to execute sequentially after verifying the value returned from the first service call. Here are the three separate effects I have: @Eff ...

Transforming the Oracle JSON response into a variable in Angular 2

After successfully setting up a service using Express API and Node to retrieve data from an Oracle DB, I am facing an issue with mapping the JSON response to an Angular variable. Even though I have created an Angular service and component, I can't see ...

Receiving numerous inputs from a single text box using Angular

I'm facing an issue when trying to accept input as an array in Angular. Below is my code snippet: <input type="number" [(ngModel)]="valuesArray"> <button (click)="PerformAction()" > find</button> va ...

Angular 15 RouterOutlet: The Ultimate Routing Solution

I'm encountering an issue while trying to run my Angular project. X [ERROR] NG8001: 'router-outlet' is not recognized: If 'router-outlet' is an Angular component, please ensure it is included in this module. If 'router-outle ...

The positioning of the legend in ngx-charts seems to be off

Greetings to all developers, I have been utilizing ngx-charts for my charting needs, and overall, everything has been working well. However, I am encountering an issue when attempting to change the position of the legend to below the chart. It seems to ex ...

Avoid Inferring as a Union Type

I am currently working on implementing a compact type-safe coordinate management system in TypeScript. It revolves around defining the origin of the coordinate as a type parameter, with functions that only accept one specific origin type. Below is a short ...

Saving JSON data in a variable or array post subscription: What's the preferred method?

I have been receiving JSON files in the following format: {streetAddress: "Kosterlijand 20", postalCode: "3980", city: "Bunnik", country: "Netherlands"} Although the length of these files varies, the structure always remains the same: {key: "string valu ...

How can we make type assertions consistent without sacrificing brevity?

In the project I am currently working on, we have implemented a warning for typescript-eslint/consistent-type-assertions with specific options set to { assertionStyle: 'as', objectLiteralTypeAssertions: 'never' }. While I generally appr ...

Delete the right-hand p-timeline-event-opposite margin from the Angular 17 PrimeNG Timeline

I am currently utilizing the PrimeNG Timeline module to showcase a few straightforward horizontal timelines with content placed on the top side in a table format. How can I eliminate the space allocated by the .p-timeline-event-opposite section? Upon inspe ...

Route parameters that repeat multiple times (n occurrences)

When creating a route with route parameters, how can you define it to allow the same parameter to be repeated n times? For example: { path: '/route/:id1/:id2/:id3/:id4', // etc. component: SomeComponent } Is there a simpler way to ...

I am seeking a method to display formatted document texts from a file located in the asset folder within an Angular HTML document as a pop-up

Text File Content -> <b>Test</b> Below is a snippet of Angular HTML I attempted: <embed src=".\assets\docs\about\BRANCH_MASTER.txt">--> <object data=".\assets\docs&bs ...