首页 > 解决方案 > 获取 NgTemplate 中包含的所有子组件的宽度

问题描述

我在模板中有这个标记。我可以使用它遍历它的组件,get但它没有返回一个允许我深入挖掘 HTML 属性的对象。

<ng-template #container></ng-template>

我在container上面动态添加组件。

我的组件代码

@ViewChild("container", { read: ViewContainerRef }) appAsideContainer: ViewContainerRef;


for (var x = 0; x < this.appAsideContainer.length; x++) {
    let c: ViewRef = this.appAsideContainer.get(x);
    console.log(c);
}

c不给我访问权限,element或者nativeElement我可以得到offsetWidth

有没有其他方法可以实现这一目标?

标签: angulartypescriptangular9

解决方案


它可以通过rootNodes在转换为之后使用属性来实现EmbeddedViewRef

for (var x = 0; x < this.appAsideContainer.length; x++) {
  const viewRef = this.appAsideContainer.get(x) as EmbeddedViewRef<any>;
  const rootNode = viewRef.rootNodes[0];
  console.log(rootNode);
}  

推荐阅读