Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using an Angular 5.x template, but I upgrade it to Angular 6 using https://update.angular.io/ guide. Now I have this error in my constructor

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

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

...

I don't have this error in previous Angular version 5.

What was the change? I don't understand the docs :( https://angular.io/api/core/ElementRef

like image 948
FrancoVP Avatar asked Jun 05 '18 16:06

FrancoVP


1 Answers

They've changed the nativeElement property from any to a generic type.

If you want the quickly fix, then change eRef: ElementRef to eRef: ElementRef<any> which is the same as in previous versions.

This change means you can now define the class type for the DOM element that is being referenced. This will assist in TypeScript compiling to enforce that type, and also IDE auto-complete features.

There are many different class types, but the base class Element is used for most DOM elements. If you know it's going to be a <input> element you can use HTMLInputElement as an example.

In your example the component is injecting it's DOM element for the constructor. Which would be a generic HTMLElement. So the code would be updated like this:

constructor(private eRef: ElementRef<HTMLElement>) {
     const title = eRef.nativeRef.title;
     // ^^^ the above title property is now verified by TypeScript at compile-time
}
like image 171
Reactgular Avatar answered Sep 22 '22 16:09

Reactgular