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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44479457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:33:33  来源:igfitidea点击:

Angular 2/4 set focus on input element

javascriptangular

提问by Dev

How can I set focus on an input by (click) event? I have this function in place but I'm clearly missing something (angular newbie here)

如何通过(单击)事件将焦点设置在输入上?我有这个功能,但我显然错过了一些东西(角度新手在这里)

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

回答by Doguhan Uluca

You can use the @ViewChilddecorator for this. Documentation is at https://angular.io/api/core/ViewChild.

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

Here's a working plnkr: http://plnkr.co/edit/KvUmkuVBVbtL1AxFvU3F

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

This gist of the code comes down to, giving a name to your input element and wiring up a click event in your template.

这段代码的要点归结为,为您的输入元素命名并在您的模板中连接一个点击事件。

 <input #myInput />
 <button (click)="focusInput()">Click</button>

In your component, implement @ViewChildor @ViewChildrento search for the element(s), then implement the click handler to perform the function you need.

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

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

  focusInput() {
    this.inputEl.nativeElement.focus()
  }

Now, click on the button and then the blinking caret will appear inside the input field. Use of ElementRefis not recommended as a security risk, like XSS attacks (https://angular.io/api/core/ElementRef) and because it results in less-portable components.

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

Also beware that, the inputElvariable will be first available, when ngAfterViewInitevent fires.

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

回答by Kapil Thakkar

Get input element as native elements in ts file.

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

//HTML CODE

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

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

  onSetFocus() {
     setTimeout(()=>{
      this.trgFocusEl.nativeElement.focus();
    },100);
  }

we need to put this.trgFocusEl.nativeElement.focus();in setTimeout()then it'll work fine otherwise it will throw undefined error.

我们需要this.trgFocusEl.nativeElement.focus();输入setTimeout()然后它会正常工作,否则它会抛出未定义的错误。

回答by M.Laida

try this.

尝试这个。

//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;
            }
        }           
    }
}

回答by Mohamed Ali RACHID

try this :

尝试这个 :

in you HTMLfile:

在你的HTML文件中:

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

<!-- Input to focus -->
<input #toFocus> 

in your tsFile :

在您的ts文件中:

sTbState: string = 'invisible';

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