StephenRios StephenRios - 1 month ago 9
TypeScript Question

Get reference to currently active HTMLElement

So I have an Angular 2 and Typescript project, and I want to clear all focus on the page on a specific click.

Right now I am just using

document.activeElement
to get the currently active element, and then calling
.blur()
on it. However this is not symantically correct, and of course TypeScript is throwing a fit about it (and rightfully so).

Is there any way I can accomplish the same thing, but ensure that I am referencing an
HTMLElement
instead of
Element
so I can keep things typed correctly?

Basically I am calling a function to close all sub-menus when A) The sub-nav is clicked and the menu item clicked is already open, and B) When the document is clicked anywhere that's not a menu item.

Here is the function that is called:

closeMenus = function(){
for (var i=0, j=this.openElements.length; i<j; i++){
this.openElements[i] = false;
};

document.activeElement.blur();
};


This gives the error:

Property 'blur' does not exist on type 'Element'


Which is absolutely correct, it exists on
HTMLElement
. However if I add this line:

console.log(document.activeElement instanceof HTMLElement);


This returns true. So I am extremely confused about exactly what TypeScript wants here?

Answer

Inject a Renderer into your component/directive.

Get a hold of any elementRef (for example your button or link).

constructor(private elRef: ElementRef, private renderer: Renderer){
}

then in your handler function:

this.renderer.invokeElementMethod(
     this.elRef.nativeElement.ownerDocument.activeElement, 'blur');