Javascript 原生 DOM 元素的 Angular 2 onload 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38409640/
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
Angular 2 onload event for a native DOM element
提问by Pho Huynh
My ultimate goal is to make a textarea element autofocus on creating. I have just thought of a solution to call e.target.focus()
on event onload
. Something like:
我的最终目标是让 textarea 元素自动聚焦于创建。我刚刚想到了一个调用e.target.focus()
event的解决方案onload
。就像是:
<textarea rows="8" col="60" (load)='handleLoad($event)'>
and then:
进而:
handleLoad(e){
e.target.focus();
}
The problem is angular does not recognize load
event.
问题是 angular 无法识别load
事件。
PS: I tried autofocus
once but it seems not working.
PS:我试过autofocus
一次,但似乎不起作用。
回答by dfsq
You should be able to do it in ngAfterViewInit hook:
你应该能够在 ngAfterViewInit 钩子中做到这一点:
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core'
// ...
export class Component implements AfterViewInit {
@ViewChild('textarea') textarea: ElementRef
ngAfterViewInit() {
this.textarea.nativeElement.focus()
}
}
Where in template you need to set template variable:
在模板中您需要设置模板变量的位置:
<textarea #textarea rows="8" col="60"></textarea>
回答by jessepinho
Try the HTML5 autofocus
attribute:
<textarea rows="8" col="60" autofocus>
Always better (and a lot simpler!) to use the native DOM API if possible than to do it in JavaScript :)
如果可能的话,使用原生 DOM API 总是比使用 JavaScript 更好(而且更简单!) :)
EDIT: The above is incorrect. See my commentbelow.