【问题标题】:Angular viewChild get offset widthAngular viewChild 获取偏移宽度
【发布时间】:2021-03-14 11:31:57
【问题描述】:

安古拉 11 // REMARK THIS HAPPENS WITH ALL THE OFFSETS BUT GET THE ID PER EXAMPLE WORKS

所以我们有几个@ViewchildsElementRefs 想要获得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


【解决方案1】:

这就是我如何根据我的情况获得父元素视图子视图的宽度。我能够使用“OnInit”和“AfterViewInit”成功地对此进行测试。

/** Left Column */
@ViewChild('gridLeftColumn', { static: true })
public gridLeftColumn: ElementRef;

const columnWidth: number = (this.gridLeftColumn.nativeElement as HTMLElement).clientWidth;

console.log('Column Width: ', columnWidth); // 760

【讨论】:

    【解决方案2】:
    ngAfterViewInit() {
          console.log(this.el.nativeElement.clientWidth); //return 0
      }
    
    
    ngAfterViewInit() {
        setTimeout(() => {
          console.log(this.el.nativeElement.clientWidth); // return 84 (true)
        }, 100);
      }
    

    我有一个“指令”,并且找到了“指令”的解决方案。只需添加一点超时。祝你有美好的一天!

    【讨论】:

      猜你喜欢
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 2019-01-20
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      相关资源
      最近更新 更多