All files / app/directive autofocus.directive.ts

85.71% Statements 18/21
84.61% Branches 11/13
60% Functions 3/5
82.35% Lines 14/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 4174x         74x     29x     29x     29x 29x   29x           28x       28x 15x 15x 15x 15x 15x                
import { Directive, ElementRef, Input } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs';
 
@Directive({ selector: '[appAutofocus]', })
export class AutofocusDirective {
 
  @Input('appAutofocus')
  enabled: boolean | '' = true;
 
  @Input()
  select = true;
 
  constructor(
    private elementRef: ElementRef,
    private router: Router,
  ) {
    router.events.pipe(
      filter(event => event instanceof NavigationEnd),
    ).subscribe(() => this.focus());
  };
 
  ngOnInit(): void {
    this.focus();
  }
 
  focus() {
    if (this.enabled === false) return;
    this.enabled = false;
    this.elementRef.nativeElement.focus();
    Eif ('setSelectionRange' in this.elementRef.nativeElement) {
      try {
        this.elementRef.nativeElement.setSelectionRange(0, this.elementRef.nativeElement.value?.length || 0);
      } catch (e) {
        console.log('no selection range??');
      }
    }
  }
 
}