【问题标题】:How to observe when a element size changes in Angular 2如何观察Angular 2中元素大小何时发生变化
【发布时间】:2026-02-17 20:30:01
【问题描述】:

当模板中的 div 改变大小时,执行某些操作的最佳方法是什么?调整窗口大小时,div 的大小会发生变化。使用 Rxjs Observable/subscribe 还是其他方式?

模板:

<div #eMainFrame class="main-frame">
   ...
</div>

组件:

@Component({
   selector: 'app-box',
   templateUrl: './box.component.html',
   styleUrls: ['./box.component.css']
})
export class BoxComponent implements OnInit {
   @ViewChild('eMainFrame') eMainFrame : ElementRef;

   constructor(){}

   ngOnInit(){
     // This shows the elements current size
     console.log(this.eMainFrame.nativeElement.offsetWidth);
   }
}

更新的组件(此示例检测窗口大小何时更改)

constructor(ngZone: NgZone) { 

   window.onresize = (e) => {
     ngZone.run(() => {
       clearTimeout(this.timerWindowResize);
       this.timerWindowResize = setTimeout(this._calculateDivSize, 100);
     });
   }
}

_calculateDivSize(){
   console.log(this.eMainFrame.nativeElement.offsetWidth); 
}

但这给了我一个错误:

异常:无法读取未定义的属性“nativeElement”

【问题讨论】:

标签: javascript angular


【解决方案1】:

浏览器不提供任何内容,因此您需要轮询该值

ngDoCheck() 在 Angular 运行变更检测时被调用。我认为这是进行检查的好地方:

ngDoCheck() {
  console.log(this.eMainFrame.nativeElement.offsetWidth);
}

如果只需要在组件创建后检查一次,使用

ngAfterContentInit(){
  // This shows the elements current size
  console.log(this.eMainFrame.nativeElement.offsetWidth);
}

【讨论】:

  • ngDoCheck 有效,但 ngDoCheck() 会被调用很多次。
  • 每次更改检测运行。这取决于您的确切要求,以及您是否可以利用某个事件来获得更好的时间来读取大小。
最近更新 更多