简体   繁体   中英

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

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
}

I fix the problem.

What I did was just run npm i @angular-cli --save and it changed from version 6.0.7 to 6.0.8, I also updated it globally. Then I run ng update @angular/cli but it doesn't change anything in my package.json. Now I can use ElementRef alone, or ElementRef<HTMLElement> or ElementRef<HTMLElement, any> , EVERYTHING WORKS NOW. I don't understand what angular-cli has to do with my tslint or typescript install, but thats the only thing I did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM