-- 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.
To check whether a specific element has focus, it's simpler: var input_focused = document. activeElement === input && document. hasFocus();
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.
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.
If the document does not have focus, ActiveElement returns null .
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With