When upgrading from ng15 to ng16, beware of the error message stating that the type '(event: RouterEvent) => void' cannot be assigned to type '(value: Event_2) => void.'

section, I encountered issues with my Angular project after upgrading from ng15 to ng16. Specifically, errors are arising when trying to implement the code snippet below. Can anyone provide insights on what may be causing problems with the event argument in this particular construction?
if (this.menuOpenSubscription === undefined) {
   this.menuOpenSubscription = this.router.events.subscribe(
    (event: RouterEvent) => this.handleNavigationEnd(event)); // Error in ng16
}
Upon compilation, the following errors were reported:
> Overload 1 of 2, '(observerOrNext?: Partial<Observer<Event_2>> |
> ((value: Event_2) => void)): Subscription', gave the following error.
> [1]     Argument of type '(event: RouterEvent) => void' is not
> assignable to parameter of type 'Partial<Observer<Event_2>> | ((value:
> Event_2) => void)'. [1]       Type '(event: RouterEvent) => void' is
> not assignable to type '(value: Event_2) => void'. [1]         Types
> of parameters 'event' and 'value' are incompatible. [1]           Type
> 'Event_2' is not assignable to type 'RouterEvent'. [1]            
> Type 'ActivationEnd' is missing the following properties from type
> 'RouterEvent': id, url [1]   Overload 2 of 2, '(next?: (value:
> Event_2) => void, error?: (error: any) => void, complete?: () =>
> void): Subscription', gave the following error. [1]     Argument of
> type '(event: RouterEvent) => void' is not assignable to parameter of
> type '(value: Event_2) => void'. [1]       Types of parameters 'event'
> and 'value' are incompatible. [1]         Type 'Event_2' is not
> assignable to type 'RouterEvent'.

Answer №1

To resolve this issue, we can utilize the Event feature from the @angular/router. Check out the example below for a working solution!

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { Subscription } from 'rxjs';
import {
  Router,
  Event,
  NavigationEnd,
  provideRouter,
  RouterModule,
} from '@angular/router';
import 'zone.js';
import { TestComponent } from './test/test.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterModule],
  template: `
    <h1>Hello from {{ name }}!</h1>
    <a routerLink="test">
      go to route
    </a>
    <router-outlet/>
  `,
})
export class App {
  menuOpenSubscription!: Subscription;
  name = 'Angular';

  constructor(private router: Router) {
    if (this.menuOpenSubscription === undefined) {
      this.menuOpenSubscription = this.router.events.subscribe((event: Event) =>
        this.handleNavigationEnd(event)
      );
    }
  }

  handleNavigationEnd(e: Event) {
    if (e instanceof NavigationEnd) {
      console.log('navigation end');
    }
  }
}

bootstrapApplication(App, {
  providers: [
    provideRouter([
      {
        path: 'test',
        component: TestComponent,
      },
    ]),
  ],
});

Check out the StackBlitz example here!

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

Access Gateway Authentication

I need assistance with integrating authentication via Shibboleth and ADFS in my Angular application. Upon navigating to the /login path, users are directed to the ADFS page to enter their credentials. After successful login, they should be redirected to ...

React | Utilizing ForwardedRefs with React Components

I'm currently working on a React project where I am creating a custom component that needs to be exported using forwardedRef. However, as I attempt to do this, an error keeps popping up: error This is the code snippet causing the issue: export inter ...

How can I structure the response from HttpClient to make it compatible with *ngFor

I need assistance in solving a minor issue. I am working with data from a REST API, which is returned as an array of objects. After receiving this data in my service, I attempt to transform it and push it to a subject to notify my component about the arriv ...

Angular - personalized modal HTML

I am facing a challenge where I need to trigger a popup when a button is clicked. There can be multiple buttons, each with its own overlay popup, and these popups should close when clicking outside of them. Currently, I am using TemplateRef (#toggleButton ...

Guide to releasing a NestJs library on npm using the nrwl/nx framework

Struggling with creating a publishable NestJS library using NX. Despite reading numerous documentations, I still can't figure it out. I've developed a NestJS library within an NX monorepository and now I want to publish just this library on NPM, ...

Is it possible to leverage lifecycle hooks within Angular Guards?

I have been working with Angular and in my project, the action for loading data on first page load is dispatched from a guard. I recently made modifications to the guard to allow access to the store. I subscribe to the store in the constructor to access th ...

Expressjs - Error: Headers already sent to the client and cannot be set

After testing various solutions from others, I am still unable to resolve this error. My objective is to iterate through each item in the array sourced below: novel.ts export let indexList = (req: Request, res: Response) => { novel.getAllDocuments ...

Binding user input to a preset value in Angular with data binding

My goal is to have a predefined input form with the email provider value preset. However, when I try to submit the form without modifying it, it does not upload anything to Firebase unless I manually delete the value and re-enter it. <input class="butt ...

Using template literals with Optional chaining in Javascript does not yield the expected results

Trying to implement template literal with optional chaining. type Item = { itemId:number, price: number}; type ItemType = { A:Item, B:Item }; const data : ItemType = { A:{itemId:1, price:2}, B:{itemId:2, price:3} }; let key = `data?.${variable}?.ite ...

Tips on switching the default camera with ngx-scanner-qrcode library in Angular

In my current project, I am utilizing the ngx-sanner-qrcode library for QRCode scanning. However, I am interested in changing the default camera from front to back in order to enhance the user experience. I assumed that I could change the default camera b ...

Different categories of properties within a generic function

I'm attempting to modify certain fields of my object using field names. Here is the code snippet I have written: interface Foo { a: number[], b: string[], } type Bar = { [T in keyof Foo] : (arg : Foo[T]) => Foo[T] } function test<T ex ...

Disable the yellow curly error lines in Visual Studio Code

Currently, I am utilizing VSCode with ESlint for Typescript development. I'm curious about how to turn off or remove the yellow curled error lines in my code editor, like the ones displayed in this example image: https://i.stack.imgur.com/Zdtza.png M ...

Asynchronous jQuery operations using promises and finally functionality

I am attempting to interact with a REST api using jQuery's ajax feature. My goal is to return the Promise<Customer> object, but I am encountering an error stating that the property finally is missing. It used to work before, so I assume there h ...

Is it possible that React useState is not allowing a default value to be set in this case?

In my chart component, I have the functionality to show/hide specific lines. To keep track of active lines, I maintain an array called activeKeys in a state. Initially, I populate this array by calling a function named getKeys, which takes an array of data ...

"Exploring the Power of TypeScript Types with the .bind Method

Delving into the world of generics, I've crafted a generic event class that looks something like this: export interface Listener < T > { (event: T): any; } export class EventTyped < T > { //Array of listeners private listeners: Lis ...

Efficiently resolving Angular's ngFor issues with Float functionality

I am currently developing a rating system that allows for half-star ratings, such as 3.5 or 4.5. Below is the code I have written: <div class="rating"> <i class="icon-star voted" *ngFor="let j of Arr(item.nbEtoile); let i = index;"></i& ...

When attempting to instantiate a list from JSON in Angular, the type '{}' is lacking the following properties compared to type 'Datos[]'

I'm encountering issues when trying to incorporate JSON data into my Angular application. My Process: Importing the JSON file into a variable: import _data from '../../../assets/data.json'; Following the advice from responses in this t ...

Exploring the Vue 3 Composition API with TypeScript and Working with Object Keys

Exploring the Vue-3 composition API and seeking guidance on utilizing types with TypeScript in Vue. Looking for more detailed information on how to define object properties and specify keys in TypeScript within the composition API, as the current document ...

Searching for an Angular component in Selenium

After reviewing the HTML code snippet below, <div class="dx-filterbuilder-action-icon dx-icon-plus dx-filterbuilder-action" tabindex="0"> ::before </div> I attempted to locate this element using Selenium C# with the followin ...

Storing data received from httpClient.get and utilizing it in the future after reading

Searching for a solution to read and store data from a text file, I encountered the issue of variable scope. Despite my attempts to use the data across the project by creating a global variable, it still gets cleared once the variable scope ends. import ...