How can I set focus to another input?

后端 未结 4 2031
天涯浪人
天涯浪人 2020-12-08 04:55

I need to be able to switch focus to an input element when some event occurs. How do I do that in Angular 2?

For example:



        
4条回答
  •  执念已碎
    2020-12-08 05:20

    Set focus - Angular 2/5

    
    
    import { Component, ViewChild, ElementRef } from '@angular/core';
    
    @Component({
      selector: 'app-general',
      templateUrl: './general.component.html',
      styleUrls: ['./general.component.scss']
    })
    export class GeneralComponent {
    
      @ViewChild("inputBox") _el: ElementRef;
    
      setFocus() {
        this._el.nativeElement.focus();
      }
    }
    

    For setting focus on load

    ngAfterViewInit() {
        this._el.nativeElement.focus();
      }
    

    You can update this logic accordingly for key press.

    More Info

提交回复
热议问题