Search code examples
angulartypescriptcastingangular5elementref

Compare HTMLElement with ElementRef


I am working in angular 5. I am invoking a function on keyup and passing an event to it. I also have another reference like this

@ViewChildren('list') list: QueryList<ElementRef>;

I am trying to check their ids and based on that do something.

But I am getting an error as

[ts] Operator '===' cannot be applied to types 'string' and 'HTMLAnchorElement'

Can someone tell me how to typecast and check their ids. Thanks. I am new to this.

handleEvent(event: KeyboardEvent) {
const tabKey = 9;
if (event.keyCode === tabKey && !event.shiftKey) {
  const el: HTMLElement = event.target as HTMLElement;

  if (el.id === <HTMLAnchorElement>this.list.first.nativeElement.id) {

    }
  }
} 

Solution

  • you can try

    if (el.id === this.list.first.nativeElement.id)
    

    and should be able to compare!