Angular 2/4 set focus on input element

后端 未结 4 1094
渐次进展
渐次进展 2021-01-07 20:48

How can I set focus on an input by (click) event? I have this function in place but I\'m clearly missing something (angular newbie here)

sTbState: string = \         


        
4条回答
  •  迷失自我
    2021-01-07 21:18

    You can use the @ViewChild decorator for this. Documentation is at https://angular.io/api/core/ViewChild.

    Here's a working plnkr: http://plnkr.co/edit/KvUmkuVBVbtL1AxFvU3F

    This gist of the code comes down to, giving a name to your input element and wiring up a click event in your template.

     
     
    

    In your component, implement @ViewChild or @ViewChildren to search for the element(s), then implement the click handler to perform the function you need.

    export class App implements AfterViewInit {
      @ViewChild("myInput") inputEl: ElementRef;
    
      focusInput() {
        this.inputEl.nativeElement.focus()
      }
    

    Now, click on the button and then the blinking caret will appear inside the input field. Use of ElementRef is not recommended as a security risk, like XSS attacks (https://angular.io/api/core/ElementRef) and because it results in less-portable components.

    Also beware that, the inputEl variable will be first available, when ngAfterViewInit event fires.

提交回复
热议问题