角度2:将视图/DOM注入组件构造函数 [英] Angular 2: Inject view/DOM into component constructor
问题描述
我不知道如何在显示表单时为组件提供对其视图的引用,以进行诸如将重点放在输入元素上的事情.我似乎无法将Element
或ng.core.ViewRef
或ng.core.View
注入到构造函数中.如何获得对视图的访问权限?
I can't figure out how to give a component a reference to its view, to do things like focus on input elements when the form is shown. I can't appear to inject Element
or ng.core.ViewRef
or ng.core.View
into the constructor. How can I get access to the view?
在Angular 1中,我将使用$ link.
In Angular 1, I would do this with $link.
推荐答案
您正在寻找的可能是ElementRef
及其nativeElement
字段,但是您应该避免以这种方式访问DOM.
我认为一种更好的方法是添加一个像<input #inp>
这样的模板变量,并使用@ViewChild('inp') input
对其进行访问.在ngAfterViewInit
input
中引用了输入元素.
What you are looking for is probably ElementRef
and its nativeElement
field, but you should avoid accessing the DOM this way.
I think a better way is to add a template variable like <input #inp>
and the access it with @ViewChild('inp') input
. In ngAfterViewInit
input
references the input element.
另请参见 angular 2/typescript:获取模板中的元素
这篇关于角度2:将视图/DOM注入组件构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!