Angular2+ autofocus input element

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

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



        
10条回答
  •  萌比男神i
    2020-12-07 18:55

    You could assign the input element a template reference variable #myInput:

    
    

    Let your component implement AfterViewInit, grab the reference of the input element with the ViewChild annotation and focus your element in the ngAfterViewInit hook:

    export class MyComponent implements AfterViewInit {
        @ViewChild("myInput") private _inputElement: ElementRef;
    
        [...]
    
        ngAfterViewInit(): void {
            this._inputElement.nativeElement.focus();
        }
    }
    

提交回复
热议问题