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

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

Angular 2 onload event for a native DOM element

javascripthtmlangular

提问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 loadevent.

问题是 angular 无法识别load事件。

PS: I tried autofocusonce 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 autofocusattribute:

尝试HTML5autofocus属性

<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.

编辑:以上是不正确的。看下面的评论