角度2:将视图/DOM注入组件构造函数

角度2:将视图/DOM注入组件构造函数

问题描述:

我不知道如何在显示表单时为组件提供对其视图的引用,以进行诸如将重点放在输入元素上的事情.我似乎无法将Elementng.core.ViewRefng.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:获取模板中的元素