18

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

Tobias Gassmann
  • 11,399
  • 15
  • 58
  • 92
  • 1
    check this https://stackoverflow.com/questions/46211183/angular-get-nested-element-using-directive-on-parent – k11k2 Sep 20 '17 at 10:25

1 Answers1

41

You need to use read option:

@ViewChild('wanted', {read: ElementRef}) myWantedChild: ElementRef;
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • If you use a mocked component to create myWantedChild in a test, when using `{ read: ElementRef }` in `@ViewChild, causes the mock to be ignored in the test. Anyone got a solution for this? – Tom Oakley Dec 06 '17 at 12:06
  • @TomOakley, I think you should create a separate question – Max Koretskyi Dec 07 '17 at 10:30
  • @AngularInDepth.com already done - https://stackoverflow.com/questions/47673211/using-viewchild-read-elementref-of-component-causes-unit-test-to-fail. Rewritten my component to fix it, writing an answer now. – Tom Oakley Dec 07 '17 at 10:31