Angular2 - Focusing a textbox on component load

前端 未结 10 1537
刺人心
刺人心 2020-12-02 16:29

I am developing a component in Angular2 (Beta 8). The component has a textbox and a dropdown. I would like to set the focus in textbox as soon as component is loaded or on c

10条回答
  •  醉梦人生
    2020-12-02 17:07

    Directive for autoFocus first field

    import {
      Directive,
      ElementRef,
      AfterViewInit
    } from "@angular/core";
    
    @Directive({
      selector: "[appFocusFirstEmptyInput]"
    })
    export class FocusFirstEmptyInputDirective implements AfterViewInit {
      constructor(private el: ElementRef) {}
      ngAfterViewInit(): void {
        const invalidControl = this.el.nativeElement.querySelector(".ng-untouched");
        if (invalidControl) {
          invalidControl.focus();
        }
      }
    }

提交回复
热议问题