Error in Typescript: TS2314 - The Generic type 'ElementRef<T, any>' needs to have 2 type arguments specified

After switching my Angular 5.x template to Angular 6 using the guidance provided at https://update.angular.io/, I encountered an error in my constructor.

Typescript Error: TS2314: Generic type 'ElementRef<T, any>' requires 2 type argument(s)

Here's a snippet of my code:

import { Component, Input, Output, EventEmitter, ElementRef, HostListener }          from '@angular/core';

@Component({
  selector: 'sidebar',
  templateUrl: './sidebar.component.html'
})

export class SidebarComponent {

    @HostListener('document:click', ['$event'])
  clickout(event) {
    if(!this.eRef.nativeElement.contains(event.target)) {
          this.hideMobileSidebar.emit(true);
    }
  }

  constructor(private eRef: ElementRef) {
  }

...

The error was not present in the previous version, Angular 5. What could have caused this change? I find it challenging to comprehend the documentation provided at https://angular.io/api/core/ElementRef.

Answer №1

The nativeElement property has undergone a transformation, transitioning from type any to a more specific generic type.

If you're looking for a quick fix, simply adjust eRef: ElementRef to eRef: ElementRef<any>, maintaining consistency with previous versions.

This alteration allows you to explicitly define the class type of the referenced DOM element. This not only aids TypeScript in enforcing that particular type during compilation but also enhances IDE auto-complete functionalities.

While there exists a variety of class types, the fundamental Element class is commonly used for most DOM elements. For instance, if you anticipate the element to be an <input> element, you can specify HTMLInputElement as an illustration.

In the provided example, the component injects its DOM element into the constructor, which should be of generic type HTMLElement. In this scenario, the code snippet would be revised as follows:

constructor(private eRef: ElementRef<HTMLElement>) {
     const title = eRef.nativeRef.title;
     // ^^^ TypeScript now verifies the 'title' property at compile-time
}

Answer №2

The issue has been resolved.

To fix the problem, I simply executed npm i @angular-cli --save, updating it from version 6.0.7 to 6.0.8 and including a global update. Following this, I ran ng update @angular/cli, although it did not reflect any changes in my package.json file. Now, I am able to use ElementRef on its own, or with ElementRef<HTMLElement> or

ElementRef<HTMLElement, any>
, and everything is functioning properly. It remains unclear how angular-cli relates to my tslint or typescript installation, but that was the sole action that resolved the issue.

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

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...

Having issues with Angular 10 changes not updating after deployment on IIS?

Every time I update the code in the .html or .js file, my changes aren't reflected in the browser. The old code persists and the new additions don't show up in the browser output. <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12"> ...

Encountering a problem when making a HTTPS GET request to a REST API using

I am currently running an Angular application that utilizes an external API to fetch country ISOs. However, I am encountering an error with the API since it uses HTTPS. Interestingly, when I implement a proxy in my Angular local environment by mapping /is ...

Equivalent Types that Do Not Compile

After reading the article on Building Complex Types in TypeScript Part 2, I encountered issues with the Equal Type code provided: Implementing Type Equality type Equal<A, B> = (<T>() => T extends A ? true : false) extends (<T> ...

Leveraging latitude and longitude data from an API to create circles on the AGM platform

I need assistance with utilizing location data from recent earthquake events to center a circle on Angular Google Maps. Can anyone provide guidance on how to achieve this? The API call provides the following data: 0: --geometry: ---coordinates: Array( ...

The Clerk authMiddleware() function has been defined in the middleware.ts file located at the root of the application, but it is not being utilized

import { authMiddleware } from "@clerk/nextjs"; export default authMiddleware({}); export const config = { matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)&apos ...

"Experiencing sluggish performance with VSCode while using TypeScript and Styled Components

My experience with vscode's type-checking is frustratingly slow, especially when I am using styled components. I have tried searching for a solution multiple times, but have only come across similar issues on GitHub. I attempted to read and understa ...

Explore the differences between the "date" type in HTML and the Date object in Typescript

Here is some code in HTML: <div class="form-group row"> <label class="col-sm-2 col-form-label">Due date: </label> <div class="col-sm-10"> <input type="date" class="form-control" #due_date> ...

Several mat-radio-button options chosen within mat-radio-group

`<mat-radio-group [ngClass]="cssForGroup" name="test"> <mat-radio-button *ngFor="let option of options | filter:searchText" class="cssForRow" [value]="option" ...

Combining the redux toolkit function createAsyncThunk with Angular's HttpClient by leveraging the ApiService

Currently, I am working on incorporating @reduxjs/toolkit into an Angular project. Is there a way to pass an Angular service as a parameter to the callback of createAsyncThunk instead of utilizing fetch directly? I referenced the documentation for an exa ...

The getStaticProps() function in NextJS has not been invoked

Currently, I am working on a basic website and my goal is to retrieve data from an API and showcase it on my component. However, I've encountered an issue where the getStaticProps() method doesn't seem to be triggering. Below is the code snippet ...

Utilize the class or interface method's data type

In the context of a child component calling a callback provided by its parent, this situation is commonly seen in AngularJS. As I am utilizing TypeScript, I aim to implement strong typing for the callback in the child component. Here is the initial stat ...

What is the best access modifier to use for TypeScript properties and functions in Angular 2 that will be accessed in the view?

Which access modifier is recommended for ng2 properties and methods that should only be used from the view? I usually use private, but came across this post advising against it: Angular2 - should private variables be accessible in the template? However, ...

Can Material UI be defined as a peerDependency while maintaining its types as a DevDependency?

Is there a way to set Material UI as a peerDependency while keeping its types as DevDependency? I'm currently working on a component library using React + Typescript, with components based on Material UI and Rollup as the module bundler. For example ...

Steer clear of utilizing the "any" type in your Express.js application built with

I have a node/express/typescript method that looks like this: // eslint-disable-next-line export const errorConverter = (err: any, req: any, res: any, next: any) => { let error = err if (!(error instanceof ApiError)) { const statusCode = e ...

The issue of Angular 2.3.1 custom validator promise not resolving

I am currently working on implementing a sign up form in which I need to check if the username is already taken or not. To accomplish this, I have decided to use promises. The structure of my sign-up component is as follows: import { Component, OnInit } f ...

Ways to implement material-ui button design on an HTML-native button

I am using pure-react-carousel which provides me an unstyled HTML button (ButtonBack). I would like to customize its style using material-ui. Trying to nest buttons within buttons is considered not allowed. An approach that works is manually assigning th ...

Deactivating a button using intricate conditions in an html document

Apologies for the vague title, I couldn't find help on Google either. I'm trying to implement the following code that doesn't seem to be working: <button [disabled]="condition1 || condition2 || (condition3 && condition4)">Save ...

Mastering the art of shaping state in NGRX for the master-detail pattern

Imagine a scenario where I am developing a compact app for organizing tasks. This app makes use of angular and NGRX to efficiently manage the state. Each day, the user loads tasks in the morning and then travels to different locations to complete them. Th ...

Separate the date format string into tokens

I am currently attempting to create a function that is able to transform a date format string such as %d/%m/%Y %H:%n where the variables are always denoted by a percentage sign followed by one character, into an array of tokens: ["%d", "/", "%m", "/", " ...