Angular7中如何获取子节点的ElementRef?
获取Angular 7中子节点的ElementRef规范方案
看起来你现在是通过DOM遍历的方式获取内部的jqxBulletChart元素,但这种方式依赖DOM结构,不够稳健,而且你希望将child设置为ElementRef类型,我给你两个更规范的解决方案:
方案1:直接获取jqxBulletChart组件实例(推荐)
既然你最终是要调用组件的val()方法,其实不需要绕到DOM层面,直接获取组件实例更符合Angular的组件化逻辑:
步骤1:给jqxBulletChart添加模板引用变量
修改你的模板,给内部的子弹图组件加上#bulletChart引用:
<div #charts *ngFor="let tag of _tags"> <jqxBulletChart #bulletChart style="margin-left: 10px; float: left;" [width]='50' [height]='350' [barSize]='"35%"' [labelsFormat]='"c"' [title]="''" description="{{tag.configuration.name}}" [showTooltip]='true' [labelsFormatFunction]="labelsFormatFunction" [tooltipFormatFunction]="tooltipFormatFunction" [ticks]='ticks' [ranges]='tag.value' [pointer]='pointer' [orientation]="'vertical'" > </jqxBulletChart> </div>
步骤2:通过@ViewChildren获取组件实例
在组件类中,直接获取所有jqxBulletChartComponent实例:
import { ViewChildren, QueryList } from '@angular/core'; import { jqxBulletChartComponent } from '你的组件路径'; // ... @ViewChildren('bulletChart') infoCharts: QueryList<jqxBulletChartComponent>;
步骤3:遍历调用组件方法
这样你可以直接遍历组件实例,调用val()方法,完全不需要操作DOM:
this.infoCharts.forEach((chart, index) => { const displayValue = +this._tags[index].displayValue || 0; chart.val(displayValue); });
方案2:获取jqxBulletChart对应的ElementRef
如果你确实需要拿到该组件的ElementRef(比如要做DOM操作),可以通过{ read: ElementRef }配置来指定获取的类型:
步骤1:同样给jqxBulletChart加模板引用(和方案1一样)
步骤2:配置@ViewChildren读取ElementRef
import { ViewChildren, QueryList, ElementRef } from '@angular/core'; // ... @ViewChildren('bulletChart', { read: ElementRef }) infoCharts: QueryList<ElementRef>;
步骤3:遍历获取ElementRef
现在遍历的时候,每个项都是标准的ElementRef类型:
this.infoCharts.forEach((chartElRef, index) => { // chartElRef 是 ElementRef 类型 console.log(chartElRef.nativeElement); // 如果还要调用组件方法,你需要同时获取组件实例和ElementRef,或者通过依赖注入拿到组件 });
为什么不推荐你原来的方式?
你之前通过chart.nativeElement.lastChild获取DOM元素的方式有两个问题:
- 依赖DOM结构:如果未来模板中在
jqxBulletChart前/后添加了其他子元素,lastChild就不再是目标组件,会导致代码出错。 - 类型不匹配:
lastChild返回的是原生DOM节点(HTMLElement),不是Angular的ElementRef类型,这也是你遇到类型问题的原因。
内容的提问来源于stack exchange,提问作者den_gera
相关产品推荐
相关产品推荐

