D
D
Drovosek012021-05-26 20:38:45
Angular
Drovosek01, 2021-05-26 20:38:45

How to get DOM element on event in Anuglar?

There is such a method in the project component on Angular 11, which listens for keystrokes on the keyboard

@HostListener('document:keydown', ['$event'])
  public someMethod(event: KeyboardEvent) {
    console.log('event', event);
  }

If I use the event.target property, I get a field of type EventTarget that has no properties and only 3 methods for working with events.

Actually, how do I get an element of type NodeList or HTMLCollection or something like that?
If you display the event itself in the console, then there will be a standard DOM structure of the component, but I can’t figure out how to use it from the component code.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2021-05-27
@Drovosek01

If I use the event.target property, I get a field of type EventTarget that does not have any properties

That's right, because this is a generic type that cannot know where you got this event from. The source of the event is an object that implements the EventTarget interface, and the event does not need more.
You just need to state clearly what you are getting.
@HostListener('document:keydown', ['$event', '$event.target'])
  public someMethod(event: KeyboardEvent, target: HTMLElement) {
    console.log('event', event, target);
  }

A
Andrey Sanych, 2021-05-26
@mountpoint

constructor(private el: ElementRef) { }
Then use likethis.el.nativeElement

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question