Angular 2的.focus()无法正常工作

3
我希望打开一个模态窗口,并让其中的输入框获得焦点。
在HTML文件中:
<img id='searchIcon' 
     src="images/search.png" 
     class="icon iconCenter" 
     data-toggle="modal" 
     data-target="#myModal" 
     (click)='focusSearch();' />

<div id="myModal" class="modal fade modal-container" role="dialog">
    <h3>SEARCH</h3>
    <input id='inputSearch' type="text" autofocus>
</div>

使用 autofocus 属性可以在第一次打开模态视图时获取焦点,但是在关闭并再次打开模态视图后不起作用。(在 Firefox 中根本不起作用)
在 ts 文件中。
focusSearch(){
    document.getElementById("inputSearch").focus();
}

如果有人能留下一个快速演示视频,我将不胜感激。

一个很好的指令可以让这个过程更容易 https://dev59.com/YlsW5IYBdhLWcg3w2aOK 不确定你是否可以将其用于你的用例。 - Günter Zöchbauer
@GünterZöchbauer 我不知道如何将其应用到我的工程中。 - angel
1
@PankajParkar 它已经具有自动对焦功能,但不起作用。 - angel
2个回答

1

设置焦点的示例

Html

   <button (click)="setFocus()">Set Focus</button>
    <input type="text" [(ngModel)]="term2" #inputBox>

组件

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();
  }
}

你可以根据自己的需求修改代码。另外,你可以在组件加载后立即设置焦点。例如:
 ngAfterViewInit() {
    this._el.nativeElement.focus();
  }

1
尝试一下,不使用函数。
<img id='searchIcon' src="images/search.png" class="icon iconCenter" data-toggle="modal" data-target="#myModal" (click)='myInput.focus()'>
    <div id="myModal" class="modal fade modal-container" role="dialog">
       <h3>SEARCH</h3>
       <input id='inputSearch' type="text" autofocus #myInput>
    </div>

没有起作用,显示点击事件中的#是一个错误。 - angel
现在应该可以运行了,我已经删除了 #(click)='myInput.focus()' - null canvas
不知道为什么,在我的情况下,这种方法会将焦点放在预期元素的下一个元素上。 - kyselm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接