Angular 2/4 如何设置输入框焦点

18

我如何在(click)事件中聚焦于输入框?我已经编写了这个函数,但显然有所遗漏(我是Angular新手)

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

20
你可以使用 @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),而且导致组件不够可移植,因此不建议使用。

另外,要注意的是,只有在ngAfterViewInit事件触发后,inputEl变量才会首次可用。


请问您能否提供一个关于Angular Material输入框的示例? - khoailang

11

将输入元素作为本地元素在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中起作用。 - embert

1
尝试这个:

在你的 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文件中是否忘记导入某些内容? - Dev

1
尝试这个。
//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;
            }
        }           
    }
}

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