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!
To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .
To select an element in a component template with Angular, we can assign an ref to the element in the template. Then we can use ViewChild to access it. to assign the inputEl ref to the input element. in the template.
Getting ElementRef in Component Class Create a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With