通过@ViewChild 访问组件的 nativeElement

Accessing nativeElement of a component by @ViewChild

免责声明: 我刚刚发现我的问题几乎与这个问题重复: 问题本身不一样,但接受的答案解决了我的问题

我的问题:我想使用@ViewChild 访问子组件的属性“.nativeElement”。这个问题已经在 SO 上讨论过,但是没有适合我的用例的解决方案。我将进一步参考其他问题。

这是父组件的html:

<h1>The Title</h1>

<some-child-component #wanted></some-child-component>

<some-other-component></some-other-component>

现在我尝试像这样访问#wanted-component:

@ViewChild('wanted') myWantedChild: ElementRef;

但是我在这里没有得到 ElementRef,我将得到对 SomeChildComponent-Instance 的引用,就像在接受的答案中指出的那样:

我可以在 Childcomponent 本身中获取 ElementRef,但将其注入到构造函数中。但是我需要父组件中的 ElementRef。

访问简单 div 块的 ElementRef 很容易:

<div #wanted>something</div>

这里直接通过@ViewChild-Annotation获取ElementRef(比较这里接受的答案:

现在我的问题仍然存在:如何获取用作子组件的组件的 ElementRef?我的确切用例是我想获取子组件的高度(以像素为单位)。据我所知,我需要 nativeElement-Reference。

编辑:

我可以将在子组件的构造函数中获得的 ElementRef 公开为 public 属性。但这似乎有点不对...

您需要使用 read 选项:

@ViewChild('wanted', {read: ElementRef}) myWantedChild: ElementRef;