Get incorrect offsetWidth and offsetHeight values

后端 未结 3 2083
眼角桃花
眼角桃花 2021-02-08 06:36

Here is my angular2 code.

Template

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-08 06:48

    In order to get correct offset values you can use: ngAfterContentChecked with the AfterContentChecked Interface.

    This method is called after every change detection run. So, inside this method use a flag (or counter) and setTimeOut:

    if (this.counter <= 10) {
          // this print offsetwidth of my element
          console.log('mm ' + this.container.nativeElement.offsetWidth);
    
    
          // setTimeOut allow to run another changedetection 
          // so ngAfterContentChecked will run again
          setTimeout(() => { }, 0);
    
          //you could use a counter or a flag in order to stop getting the right width
          this.counter++;
        }
    

    Hope it helps! Feel free to comment

提交回复
热议问题