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