首页 > 解决方案 > Angular:从组件中获取 nativeElement

问题描述

有没有一种简单的方法可以从组件实例中获取 nativeElement(或 ElementRef)?我从这样的视图中引用一个组件:

@ViewChild(MyComponent) myComponent: MyComponent;

我知道我可以得到 ElementRef 而不是像这样得到 MyComponent :

@ViewChild('my-component', { read: ElementRef}) myComponent: ElementRef;

如果我只需要一个 ElementRef,这很好,但我实际上需要 MyComponent 的实例,但稍后我需要将其向下转换为 ElementRef,以便我可以访问 nativeElement。

标签: angular

解决方案


从 Angular 9 开始,我不知道有一种方法可以从组件引用中获取本机元素。但是,可以同时获得两者。

@ViewChild(MyComponent) component: MyComponent;
@ViewChild(MyComponent, { read: ElementRef }) elementRef: ElementRef<HTMLElement>;

推荐阅读