Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the active Element (the focused one) on Angular 6?

-- Not duplicate! Since the other questions are outdated. Not duplicate with the asked question!!!!

this.elm.nativeElement.ownerDocument.activeElement

also

document.activeElement

gives me strangely enough the whole body.How can i just get the current focused element?

  • elm = type of ElementRef which is bound in my component's constructor.

  • from another question here: this.renderer.invokeElementMethod is also not callable since Renderer is now deprecated and Renderer2 does obviously not have that method anymore.

EDIT: This question answers this problem partially:

document.activeelement returns body

Between leaving the old element and entering the new element the active element is indeed the document/body itself.

like image 323
akcasoy Avatar asked Sep 27 '18 07:09

akcasoy


People also ask

How do I find out which DOM element has the focus?

To check whether a specific element has focus, it's simpler: var input_focused = document. activeElement === input && document. hasFocus();

How do you focus an active element?

Typically a user can press the tab key to move the focus around the page among focusable elements, and use the space bar to activate one (that is, to press a button or toggle a radio button). Which elements are focusable varies depending on the platform and the browser's current configuration.

How do you get the focus element in react?

To check if an element is focused in React:Set the ref prop on the element. After the element is rendered, check if the element is the active element in the document. If it is, the element is focused.

Can document activeElement be null?

If the document does not have focus, ActiveElement returns null .


1 Answers

I had to cover "document.activeElement" or "this.elm.nativeElement.ownerDocument.activeElement" inside a timeout, so that the active element is checked by the next angular lifecycle. Otherwise, when "X.activeElement" is executed just after the focus change, you get the whole body since while entering the new element the active element is indeed the document/body itself.

setTimeout(function() {
  X = document.activeElement;
});

Edit für ES6 (where "this" also can be used):

setTimeout(() => {
  X = document.activeElement;
});
like image 113
akcasoy Avatar answered Oct 25 '22 00:10

akcasoy