获取 Ng 模板中包含的所有子组件的宽度
Getting the width of all child components contained in an 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
还有其他方法可以实现吗?
转换为EmbeddedViewRef
后使用rootNodes
属性即可实现:
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);
}
我在模板中有这个标记。我可以使用 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
还有其他方法可以实现吗?
转换为EmbeddedViewRef
后使用rootNodes
属性即可实现:
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);
}