Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 - How to get HTMLElement / ElementRef of child component using template reference variable?

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!

like image 308
Dangular Avatar asked May 18 '17 12:05

Dangular


People also ask

How do I use a template reference variable in component?

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 .

How can I select an element in a component template?

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.

How do I access ElementRef?

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.


1 Answers

@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.

like image 148
Max Koretskyi Avatar answered Sep 27 '22 20:09

Max Koretskyi