【发布时间】:2021-03-14 11:31:57
【问题描述】:
安古拉 11 // REMARK THIS HAPPENS WITH ALL THE OFFSETS BUT GET THE ID PER EXAMPLE WORKS
所以我们有几个@Viewchilds 和ElementRefs 想要获得offsetWidth。
为此,我们有以下代码:
// container is the REF that has the HTML --> #container
@ViewChild('container') containerRef: ElementRef;
...
...
ngAfterViewInit(): void {
const containerOffset: number = this.containerRef.nativeElement.offsetWidth;
const containerOffset1: number = (this.containerRef.nativeElement as HTMLElement).offsetWidth;
}
问题是我们得到的偏移量是0。
但是如果我们执行console.log(this.containerRef),它会完美地显示内部的nativeElement,您可以看到偏移量不同于0。
有人可以帮忙吗?
(如果可能的话,不使用 document.querySelector 的解决方案.....)
【问题讨论】:
-
尝试并在 setTimeout 中获取偏移量。不要依赖console.log,打印的值可以并且将会改变,因为它是通过引用(如果它是一个对象)。改用
console.log(this.containerRef.nativeElement.offsetWidth),它可能会再次为0。 -
Okei,我的问题是为什么是 0,什么时候应该更大,比如 247?
-
因为它可能还没有完全渲染。做一个 stackblitz 例子
-
但是据说,所有必须使用@viewChild 访问的元素,您可以在ngAfterInit 上尽快访问它们吧??
标签: angular typescript dom viewchild