Angular 2/4设置焦点在输入元素上

Dev*_*Dev 14 javascript 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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Dog*_*uca 15

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

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

代码的要点归结为,给输入元素命名并在模板中连接点击事件.

 <input #myInput />
 <button (click)="focusInput()">Click</button>
Run Code Online (Sandbox Code Playgroud)

在组件中,实现@ViewChild@ViewChildren搜索元素,然后实现单击处理程序以执行所需的功能.

export class App implements AfterViewInit {
  @ViewChild("myInput") inputEl: ElementRef;

  focusInput() {
    this.inputEl.nativeElement.focus()
  }
Run Code Online (Sandbox Code Playgroud)

现在,单击按钮,然后闪烁的插入符号将出现在输入字段内.使用ElementRef不建议为安全风险,如跨站脚本攻击(https://angular.io/api/core/ElementRef),因为它会导致便携更少的组件.

还要注意inputEl,当ngAfterViewInit事件触发时,变量将首先可用.


小智 5

在ts文件中获取输入元素作为本机元素。

//HTML CODE

<input #focusTrg />
<button (click)="onSetFocus()">Set Focus</button>

//TS CODE
@ViewChild("focusTrg") trgFocusEl: ElementRef;

  onSetFocus() {
     setTimeout(()=>{
      this.trgFocusEl.nativeElement.focus();
    },100);
  }
Run Code Online (Sandbox Code Playgroud)

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


Moh*_*HID 1

尝试这个 :

在你的HTML文件中:

<button type="button" (click)="toggleSt($event, toFocus)">Focus</button>

<!-- Input to focus -->
<input #toFocus> 
Run Code Online (Sandbox Code Playgroud)

在你的ts文件中:

sTbState: string = 'invisible';

toggleSt(e, el) {
  this.sTbState = (this.sTbState === 'invisible' ? 'visible' : 'invisible');
  if (this.sTbState === 'visible') {
    el.focus();
  }
}
Run Code Online (Sandbox Code Playgroud)