【发布时间】:2018-03-01 08:36:18
【问题描述】:
免责声明:我刚刚发现我的问题几乎与此问题重复:Angular get nested element using directive on parent 问题本身不一样,但接受的答案解决了我的问题
我的问题:我想使用@ViewChild 访问子组件的属性“.nativeElement”。这个问题已经在这里讨论过,但是没有适合我的用例的解决方案。我将进一步参考其他问题。
这是父组件的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 的引用,就像在接受的答案中指出的那样: How to access the nativeElement of a Component in Angular4?
我可以在 Childcomponent 本身中获取 ElementRef,但将其注入构造函数中。但我需要父组件中的 ElementRef。
访问一个简单的 div 块的 ElementRef 很容易:
<div #wanted>something</div>
在这里,您可以通过@ViewChild-Annotation 直接获得 ElementRef(比较接受的答案:What's the proper way of accessing native element in angular2 (2 diff ways) docs are scarce
现在我的问题仍然存在:如何获取用作子组件的组件的 ElementRef?我的确切用例是我想获取子组件的高度(以像素为单位)。据我所知,我需要 nativeElement-Reference。
编辑:
我可以将在子组件的构造函数中获得的 ElementRef 公开为公共属性。但这似乎有点不对...
【问题讨论】:
标签: angular angular-components