Angular2+ autofocus input element

后端 未结 10 2006
走了就别回头了
走了就别回头了 2020-12-07 18:24

How can I autofocus input element? Similar to this question, but not with AngularDart. Something like this:



        
10条回答
  •  醉梦人生
    2020-12-07 19:15

    autofocus is a native html feature that should work at least for page initialization. However it fails to work with many angular scenarios, especially with *ngIf.

    You can make a really simple custom directive to get desired behaviour.

    import { Directive, OnInit, ElementRef } from '@angular/core';
    
    @Directive({
      selector: '[myAutofocus]'
    })
    export class AutofocusDirective implements OnInit {
    
      constructor(private elementRef: ElementRef) { };
    
      ngOnInit(): void {
        this.elementRef.nativeElement.focus();
      }
    
    }
    

    The above directive works for my use cases.

    How to use

    
    

    EDIT: There seems to be usecases where it is to early to call focus in the OnInit lifecycle method. If that is the case, change to OnAfterViewInit instead.

提交回复
热议问题