【问题标题】:Accessing nativeElement of a component by @ViewChild通过 @ViewChild 访问组件的 nativeElement
【发布时间】: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


【解决方案1】:

你需要使用read选项:

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

【讨论】:

  • 如果在测试中使用模拟组件创建 myWantedChild,当在`@ViewChild 中使用{ read: ElementRef } 时,会导致模拟在测试中被忽略。有人对此有解决方案吗?
  • @TomOakley,我认为你应该创建一个单独的问题
  • @AngularInDepth.com 已经完成 - stackoverflow.com/questions/47673211/…。重写我的组件来修复它,现在写一个答案。
猜你喜欢
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 2017-03-03
  • 2022-08-20
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多