Disclaimer: I just found out that my question is close to being a duplicate of this one: Angular get nested element using directive on parent The question in itself is not the same, but the accepted answer solves my problem
My Problem: I want to access the property ".nativeElement" of a child-component by using @ViewChild. This question has already been discussed here on SO, but there was no solution that worked for my use-case. I will reference the other questions further down.
This is the html of the parent-component:
<h1>The Title</h1>
<some-child-component #wanted></some-child-component>
<some-other-component></some-other-component>
Now I try to access the #wanted-component like this:
@ViewChild('wanted') myWantedChild: ElementRef;
But I do not get an ElementRef here, I will get the reference to the SomeChildComponent-Instance like is pointed out here in the accepted answer: How to access the nativeElement of a Component in Angular4?
I can get a hold of the ElementRef in the Childcomponent itself but injecting it in the constructor. But I need the ElementRef in the parent-component.
Accessing the ElementRef of a simple div-block is easy:
<div #wanted>something</div>
Here you get the ElementRef directly by the @ViewChild-Annotation (compare the accepted answer here:What's the proper way of accessing native element in angular2 (2 diff ways) docs are scarce
Now the question for me remains: How can I get the ElementRef of a component that is used as a child-component? My exact use-case is that I want to get the height in pixels of a child-component. As far as I know I need the nativeElement-Reference for that.
EDIT:
I could just expose the ElementRef that I get in the constructor of the child-component as a public property. But that seems a little off...
You can use exportAs property of the @Directive annotation. It exports the directive to be used in the parent view. From the parent view, you can bind it to a view variable and access it from the parent class using @ViewChild() .
You need to use read
option:
@ViewChild('wanted', {read: ElementRef}) myWantedChild: ElementRef;
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