File

libs/ui/autofocus/src/lib/autofocus/autofocus.directive.ts

Description

Autofocus any focusable element on-load.

Passing any truthy value OR an empty string will enable the autofocus.

Implements

AfterViewInit

Example

<input type="text" tsAutofocus />
<button [tsAutofocus]="true">Click Me</button>

<example-url>https://getterminus.github.io/ui-demos-release/components/autofocus</example-url>

Metadata

Selector [tsAutofocus]

Index

Inputs
Accessors

Constructor

constructor(elementRef: ElementRef, changeDetectorRef: ChangeDetectorRef)
Parameters :
Name Type Optional
elementRef ElementRef No
changeDetectorRef ChangeDetectorRef No

Inputs

tsAutofocus

Define if the element should be focused after initialization

Accessors

tsAutofocus
settsAutofocus(value)

Define if the element should be focused after initialization

Parameters :
Name Optional
value No
Returns : void
import {
  AfterViewInit,
  ChangeDetectorRef,
  Directive,
  ElementRef,
  Input,
  isDevMode,
} from '@angular/core';

import { coerceBooleanProperty } from '@terminus/fe-utilities';
import { TsUILibraryError } from '@terminus/ui-utilities';


/**
 * Autofocus any focusable element on-load.
 *
 * Passing any truthy value OR an empty string will enable the autofocus.
 *
 * @example
 * <input type="text" tsAutofocus />
 * <button [tsAutofocus]="true">Click Me</button>
 *
 * <example-url>https://getterminus.github.io/ui-demos-release/components/autofocus</example-url>
 */
@Directive({ selector: '[tsAutofocus]' })
export class TsAutofocusDirective implements AfterViewInit {
  /**
   * Store the shouldFocus value
   */
  private shouldFocus!: boolean;

  /**
   * Define if the element should be focused after initialization
   *
   * @param value
   */
  @Input()
  public set tsAutofocus(value: string | boolean) {
    this.shouldFocus = coerceBooleanProperty(value);
  }

  constructor(
    private elementRef: ElementRef,
    private changeDetectorRef: ChangeDetectorRef,
  ) {}


  /**
   * Focus the input after the view has initialized
   */
  public ngAfterViewInit(): void {
    if (this.shouldFocus) {
      const el = this.elementRef.nativeElement;

      if (el.focus) {
        el.focus();
        this.changeDetectorRef.detectChanges();
      } else if (isDevMode()) {
        throw new TsUILibraryError(`TsAutofocusDirective must be used on an element that has a .focus() method.`);
      }
    }
  }
}

result-matching ""

    No results matching ""