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

标签 javascript angular

如何通过(点击)事件设置焦点?我有这个功能,但我显然遗漏了一些东西(这里 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();
  }
}

最佳答案

您可以为此使用@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 变量将首先可用。

关于javascript - Angular 2/4 将焦点设置在输入元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44479457/

相关文章:

http - 订阅前调用函数

JavaScript 初始化函数

javascript - 如何将半填的表单数据发送到服务器?

javascript - 多个输入字段之间的表单验证

javascript - 以 Angular 将 map 转换为json对象

css - Angular 2 拖放 ngx-dnd 缺少样式

javascript - 将旧的 JavaScript 代码转换为 ES6 模块

javascript - 更改 innerHTML 时 Div 元素会移动

javascript - Bootstrap 表 - 行中的动态按钮

带有自定义事件的 Angular 4 dispatchEvent