'Angular 7 how to check if any element has focus

I'm looking to trigger a dialog function on keyup as long as no input is focused. I have searched around and I have yet to find a solution.

I have tried document.hasFocus() but that didn't work. The function triggered regardless.

Any ideas?

      @HostListener('window:keydown', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    if (this.router.url.includes('cart') || this.router.url.includes('rack') || document.hasFocus()) {
      console.log(document.activeElement);
      return;
    }
    const dialogConfig = new MatDialogConfig();
    dialogConfig.disableClose = false;
    dialogConfig.hasBackdrop = true;
    const input = String.fromCharCode(event.keyCode);
    if (this.search === '' && /[a-zA-Z0-9]/.test(input)) {
      this.search = event.key;
      dialogConfig.data = this.search;
      const dialogRef = this.dialogService.openDialog(SearchBarComponent, dialogConfig);
      dialogRef.afterClosed().subscribe(
        data => this.search = ''
      );
    }
  }


Solution 1:[1]

I figured it out.

I just need to check if the activeElement is the body.

document.activeElement === document.body

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin Wilde