【问题标题】:How to set focus on specific input?如何设置对特定输入的关注?
【发布时间】:2017-07-13 14:59:42
【问题描述】:

所以我有循环,我有输入列表。我有焦点指令,但我想将焦点放在特定输入上。这是我的笨蛋:

https://plnkr.co/edit/POP7Fh6G2bWhBEPBkTSm?p=preview

 <div *ngFor="let input of inputs">
      <input type="text" focusOnInit>
    </div>
  inputs  = [
    {name:'Superman'},
    {name:'Batman'},
    {name:'BatGirl'},
    {name:'Robin'},
    {name:'Flash'}
];

有什么建议吗?

【问题讨论】:

  • 具体输入是哪个输入?你想什么时候设置焦点?
  • 我可以每次都传值吗?
  • 什么是“每次”?请更具体地说明您要完成的工作。
  • 我有下拉菜单,在每次下拉菜单更改时,我都有不同的输入列表。所以我想更改下拉菜单以将重点放在不同的输入上。例如,如果我首先从下拉列表中选择,我将首先设置焦点,但是当我从下拉列表中选择第二个值时,我想将焦点设置在第三个输入上。

标签: angular


【解决方案1】:

你可以添加

@Input()
focusOnInit:number;

focus() {
  this.renderer.invokeElementMethod(
    this.elementRef.nativeElement, 'focus', []);
}

focusOnInit 指令,然后传递一个像

这样的 id
[focusOnInit]="input.id"

在父组件中可以查询所有focusOnInit指令

@ViewChildren(FocusOnInit) focusDirectives: FocusOnInit[];

当您想将焦点设置在特定输入上时使用

focus(id) {
  var input = this.focusDirectives.toArray().find((f) => f.focusOnInit === id);
  if(input) {
    input.focus();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多