angular 2 - 如何使用模板引用变量获取子组件的HTMLElement/ElementRef?

Dan*_*lar 10 dom autoscroll viewchild angular

我正在尝试使用ViewChild获取子组件的元素,但无法找到实现此目的的方法.

我们在模板中说:

...
<some-comp #someComp></some-comp>
...
Run Code Online (Sandbox Code Playgroud)

并获得此参考:

import { SomeComponent } from './some-comp/some-comp.component';
...
@ViewChild('someComp') someComp: SomeComponent;
...
ngOnInit() {
// this.someComp.nativeElement? <-- how to get nativeElement?
}
Run Code Online (Sandbox Code Playgroud)

我试图这样做的原因是通过使用scrollToHTMLElement的函数自动滚动到该子组件的位置来将视图集中到该子组件.(请参阅如何在单击时将元素滚动到视图中)

我可以通过给那个子组件提供id并使用document.getElementById()来检索它,但我想知道是否有办法使用模板引用变量或任何角度方式来执行此操作.

提前致谢!

Max*_*kyi 16

@ViewChilddecorator可以查询几个可以使用read参数指定的不同类型:

@ViewChild(selector, {read: Type}) property;
Run Code Online (Sandbox Code Playgroud)

这些类型可以是:

  • ElementRef

    @ViewChild('someComp', {read: ElementRef}) someComp;

  • ViewContainerRef

    @ViewChild('someComp', {read: ViewContainerRef}) someComp;

在你的情况下,这ElementRef是你想要的.