0 Comments

 

 

Just a small directive that will set focus on an focusable element:

 

import { AfterContentInitDirectiveElementRefInput } from ‘@angular/core’;

 

export const FOCUSABLE_ELEMENTS_QUERY = ‘button, [href], input, select, textarea, [tabindex]:not([tabindex=”-1″])’;

 

@Directive({

  selector: ‘[autoFocus]’,

})

export class AutofocusDirective implements AfterContentInit {

  @Input() public appAutoFocusboolean;

 

  public constructor(private elElementRef) {}

 

  public ngAfterContentInit() {

    // We first execute setTimeout to make sure Angular has rendered the component tree.

    setTimeout(() => {

      if (!this.el.nativeElement) {

        console.error(`Element does not have a nativeElement.`);

      }

 

      let elementToFocusHTMLElement;

      const nativeElementHTMLElement = this.el.nativeElement as HTMLElement;

      if (this.isFocusable(nativeElement)) {

        elementToFocus = this.el.nativeElement;

      } else {

        const focusableElements = nativeElement.querySelectorAll(FOCUSABLE_ELEMENTS_QUERY);

        if (focusableElements && focusableElements.length > 0) {

          elementToFocus = focusableElements[0as HTMLElement;

        }

      }

      if (elementToFocus) {

        elementToFocus.focus();

      } else {

        console.error(‘No focusable element found.’);

      }

    });

  }

 

  public isFocusable(elementHTMLElement): boolean {

    const tagName = element.tagName.toLowerCase();

    return (

      tagName === ‘input’ ||

      tagName === ‘button’ ||

      tagName === ‘select’ ||

      tagName === ‘textarea’ ||

      element.hasAttribute(‘href’) ||

      (element.hasAttribute(‘tabindex’) && element.tabIndex !== null && element.tabIndex !== –1)

    );

  }

}

<

p style=”background: #1e1e1e”>
 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts