I'm trying to get element of child component using ViewChild but can't find a way to achieve this.
Let's say in template:
...
<some-comp #someComp></some-comp>
...
and getting this reference by:
import { SomeComponent } from './some-comp/some-comp.component';
...
@ViewChild('someComp') someComp: SomeComponent;
...
ngOnInit() {
// this.someComp.nativeElement? <-- how to get nativeElement?
}
The reason why I'm trying to do this is to focus the view to that child component by auto scrolling to that child component's position using scrollTo
function of HTMLElement.(see How to scroll element into view when it's clicked)
I can achieve it by giving id to that child component and retrieve using document.getElementById(), but I'm wondering if there's a way to do this using template reference variable or any angular way.
Thanks in advance!
@ViewChild
decorator can query several different types which can be specified using read
parameter:
@ViewChild(selector, {read: Type}) property;
Those types can be:
ElementRef
@ViewChild('someComp', {read: ElementRef}) someComp;
ViewContainerRef
@ViewChild('someComp', {read: ViewContainerRef}) someComp;
In your case it's ElementRef
that you want.