angular - 聚焦 <input> 元素

标签 angular

我在 div 中有许多 input 框,我需要以编程方式聚焦其中一个。

怎么做?

是这样的:

<div>
<input type="text" name="txt1" />
<input type="text" name="txt2" />
<input type="text" name="txt3" />
<input type="text" name="txt4" />
<input type="text" name="txt5" />
<input type="text" name="txt6" />
</div>
<button (click)="selectSample()" />

selectSample() {
    ?????????('txt3').focus();
    console.log('Button pressed, txt3 has been selected');
}

最佳答案

@Component({
  selector: 'my-app',
  template: `
<div>
<input #input type="text" name="txt1" />
<input #input type="text" name="txt2" />
<input #input type="text" name="txt3" />
<input #input type="text" name="txt4" />
<input #input type="text" name="txt5" />
<input #input type="text" name="txt6" />
</div>
<button (click)="selectSample()">click</button>
`
})
export class App {
  @ViewChildren('input') inputs;

  selectSample() {
    // console.debug(this.inputs.toArray().find((e) => {
    //  return e.nativeElement.getAttribute('name') == 'txt3';
    //}).nativeElement.value);

    this.inputs.toArray().find((e) => {
      return e.nativeElement.getAttribute('name') == 'txt3';
    }).nativeElement.focus();

  }
}

Plunker example

关于angular - 聚焦 &lt;input&gt; 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36329658/

相关文章:

angular - 始终显示工具提示(Angular Material2)

html - Angular 侧边栏与页面内容重叠

facebook - ionic /云 Angular FacebookAuth 给出空错误

angular - 如何在服务请求上使用 switchmap?

angular - 我应该在 Angular 中再次调用 ngOnInit() 吗?

javascript - Angular 2 (click) 和 (dblclick) 在同一个元素上效果不佳?

Angular 无法使用不同数量的 child 重新附加 ActivatedRouteSnapshot

angular - 以 Angular 5 过滤 Angular Material 表中的特定列

javascript - provide 函数获取的参数到底是什么?

css - SASS 嵌套(为了可读性),这是一种不好的做法吗?