【问题标题】:Angular 2/4 set focus on input elementAngular 2/4 将焦点设置在输入元素上
【发布时间】:2024-08-20 10:05:02
【问题描述】:

如何通过(单击)事件将焦点设置在输入上?我有这个功能,但我显然错过了一些东西(这里有角度的新手)

sTbState: string = 'invisible';
private element: ElementRef;
toggleSt() {
  this.sTbState = (this.sTbState === 'invisible' ? 'visible' : 'invisible');
  if (this.sTbState === 'visible') {
    (this.element.nativeElement).find('#mobileSearch').focus();
  }
}

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    您可以为此使用 @ViewChild 装饰器。文档位于https://angular.io/api/core/ViewChild

    这是一个有效的 plnkr:http://plnkr.co/edit/KvUmkuVBVbtL1AxFvU3F

    此代码要点归结为,为您的输入元素命名并在您的模板中连接一个点击事件。

     <input #myInput />
     <button (click)="focusInput()">Click</button>
    

    在您的组件中,实现@ViewChild@ViewChildren 来搜索元素,然后实现点击处理程序来执行您需要的功能。

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

    现在,单击按钮,然后闪烁的插入符号将出现在输入字段中。不建议使用ElementRef 作为安全风险, 像 XSS 攻击 (https://angular.io/api/core/ElementRef) 并且因为它导致组件的便携性降低。

    另外请注意,inputEl 变量将在ngAfterViewInit 事件触发时首先可用。

    【讨论】:

    • 你能帮忙举个例子吗?
    【解决方案2】:

    获取输入元素作为 ts 文件中的原生元素。

    //HTML CODE
    
    <input #focusTrg />
    <button (click)="onSetFocus()">Set Focus</button>
    
    //TS CODE
    @ViewChild("focusTrg") trgFocusEl: ElementRef;
    
      onSetFocus() {
         setTimeout(()=>{
          this.trgFocusEl.nativeElement.focus();
        },100);
      }
    

    我们需要将this.trgFocusEl.nativeElement.focus(); 放入setTimeout() 然后它会正常工作,否则会抛出未定义的错误。

    【讨论】:

    • 老兄,谢谢。我变得绝望让 focus() 在 ngAfterViewInit 中工作..
    【解决方案3】:

    试试这个:

    在你的 HTML 文件中:

    <button type="button" (click)="toggleSt($event, toFocus)">Focus</button>
    
    <!-- Input to focus -->
    <input #toFocus> 
    

    在您的 ts 文件中:

    sTbState: string = 'invisible';
    
    toggleSt(e, el) {
      this.sTbState = (this.sTbState === 'invisible' ? 'visible' : 'invisible');
      if (this.sTbState === 'visible') {
        el.focus();
      }
    }
    

    【讨论】:

    • 非常感谢您的回复。我试过了,但控制台上没有任何变化,也没有 DOM 错误。我是否忘记在ts 文件中导入某些内容?
    【解决方案4】:

    试试这个。

    //on .html file
    <button (click)=keyDownFunction($event)>click me</button>
    
    // on .ts file
    // navigate to form elements automatically.
    keyDownFunction(event) {
        // specify the range of elements to navigate
        let maxElement = 4;
        if (event.keyCode === 13) {
            // specify first the parent of container of elements
            let container = document.getElementsByClassName("myForm")[0];
            // get the last index from the current element.
            let lastIndex = event.srcElement.tabIndex ;
            for (let i=0; i<maxElement; i++) {
                // element name must not equal to itself during loop.
                if (container[i].id !== event.srcElement.id && 
                    lastIndex < i) {   
                    lastIndex = i;                 
                    const tmp = document.getElementById(container[i].id);
                    (tmp as HTMLInputElement).select();
                    tmp.focus();
                    event.preventDefault();
                    return true;
                }
            }           
        }
    }
    

    【讨论】: