angular - Angular 2+:获取@ViewChild() 的子元素
问题描述
如何在没有明确声明的情况下访问 Angular 2+ 中的子元素(此处<img>
:) ?@ViewChild()
在模板.html
<div #parent>
<!-- There can be anything than <img> -->
<img src="http://localhost/123.jpg" alt="">
</div>
在组件.ts
@ViewChild('parent') parent;
public getFirstChild() {
this.firstChild = this.parent.? //
}
目的是能够创建一个通用组件,该组件使用:
<div #parent>
<ng-content></ng-content>
</div>
因此需要的子元素#parent
无需显式声明即可访问。
解决方案
您可以使用given by的nativeElement
属性来获取相应的 HTML 元素。从那里,标准 DOM 方法和属性可以访问其子项:ElementRef
ViewChild
- 元素.children
- element.querySelector
- element.querySelectorAll
- 等等
例如:
@ViewChild("parent") private parentRef: ElementRef<HTMLElement>;
public getChildren() {
const parentElement = this.parentRef.nativeElement;
const firstChild = parentElement.children[0];
const firstImage = parentElement.querySelector("img");
...
}
请参阅此 stackblitz以获取演示。
推荐阅读
- javascript - 在多个日期分发事件
- python - python - 在类初始化或延迟上填充生成器?
- java - JAVA在现有的excel表格中打印输出数据
- docker - 如何将启动参数传递给 docker compose 文件,如 docker run --opts?
- yocto - 带有 bbappend 多层的 Yocto 开发图像
- google-cloud-platform - Google“Team Foundation Server 的云工具”在 VSTS Marketplace 上不可用
- ffmpeg - FFmpeg 应用多个过滤器(徽标叠加、亮度变化和文本叠加)
- python - 打印分层字典的递归方法
- sharepoint-online - 有没有办法使用共享点加载项或扩展添加列表项
- html - 屏幕调整大小时,单行显示的等宽图像不会保持在同一行