angular - Angular:从组件中获取 nativeElement
问题描述
有没有一种简单的方法可以从组件实例中获取 nativeElement(或 ElementRef)?我从这样的视图中引用一个组件:
@ViewChild(MyComponent) myComponent: MyComponent;
我知道我可以得到 ElementRef 而不是像这样得到 MyComponent :
@ViewChild('my-component', { read: ElementRef}) myComponent: ElementRef;
如果我只需要一个 ElementRef,这很好,但我实际上需要 MyComponent 的实例,但稍后我需要将其向下转换为 ElementRef,以便我可以访问 nativeElement。
解决方案
从 Angular 9 开始,我不知道有一种方法可以从组件引用中获取本机元素。但是,可以同时获得两者。
@ViewChild(MyComponent) component: MyComponent;
@ViewChild(MyComponent, { read: ElementRef }) elementRef: ElementRef<HTMLElement>;
推荐阅读
- sonarqube - 如何获得我所有项目的顶级覆盖率报告?
- android - 活动场景
挂起执行(点击()) - jestjs - Bootstrap Dropdown 未在 jestjs 单元测试中正确导入 typescript
- sql-server - SQL Server 非聚集索引扫描或索引取决于值
- c# - EF 如何创建更新具有 500 万行的 SQLite 表中的 100 万行所需的 SQL?它会逐行更新吗?
- java - 无法将 FloatBuffer 转换为 float[] (UnsupportedOperationException)
- pine-script - 如何获得最高和最低的条形指数
- angular - 如果 FormControl 有“。”,为什么 FormGroup.Get() 返回 null 在名字里?
- mysql - 在mysql中选择前半年的记录
- javascript - 如何正确更新递归函数中的变量 - 基本示例