angular 2 - 如何使用模板引用变量获取子组件的 HTMLElement / ElementRef?
angular 2 - How to get HTMLElement / ElementRef of child component using template reference variable?
我正在尝试使用 ViewChild 获取子组件的元素,但找不到实现此目的的方法。
假设在模板中:
...
<some-comp #someComp></some-comp>
...
并通过以下方式获取此参考:
import { SomeComponent } from './some-comp/some-comp.component';
...
@ViewChild('someComp') someComp: SomeComponent;
...
ngOnInit() {
// this.someComp.nativeElement? <-- how to get nativeElement?
}
我尝试这样做的原因是通过使用 HTMLElement 的 scrollTo
功能自动滚动到该子组件的位置,将视图聚焦到该子组件。(参见 )
我可以通过为该子组件提供 id 并使用 document.getElementById() 检索来实现它,但我想知道是否有办法使用模板引用变量或任何 angular方式。
提前致谢!
@ViewChild
装饰器可以查询几种不同的类型,可以使用read
参数指定:
@ViewChild(selector, {read: Type}) property;
这些类型可以是:
元素引用
@ViewChild('someComp', {read: ElementRef}) someComp;
ViewContainerRef
@ViewChild('someComp', {read: ViewContainerRef}) someComp;
在你的情况下,你想要 ElementRef
。
我正在尝试使用 ViewChild 获取子组件的元素,但找不到实现此目的的方法。
假设在模板中:
...
<some-comp #someComp></some-comp>
...
并通过以下方式获取此参考:
import { SomeComponent } from './some-comp/some-comp.component';
...
@ViewChild('someComp') someComp: SomeComponent;
...
ngOnInit() {
// this.someComp.nativeElement? <-- how to get nativeElement?
}
我尝试这样做的原因是通过使用 HTMLElement 的 scrollTo
功能自动滚动到该子组件的位置,将视图聚焦到该子组件。(参见
我可以通过为该子组件提供 id 并使用 document.getElementById() 检索来实现它,但我想知道是否有办法使用模板引用变量或任何 angular方式。
提前致谢!
@ViewChild
装饰器可以查询几种不同的类型,可以使用read
参数指定:
@ViewChild(selector, {read: Type}) property;
这些类型可以是:
元素引用
@ViewChild('someComp', {read: ElementRef}) someComp;
ViewContainerRef
@ViewChild('someComp', {read: ViewContainerRef}) someComp;
在你的情况下,你想要 ElementRef
。