StephenRios StephenRios - 1 year ago 194
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

to get the currently active element, and then calling
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
instead of
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;


This gives the error:

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

Which is absolutely correct, it exists on
. 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 Source

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.elRef.nativeElement.ownerDocument.activeElement, 'blur');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download