如何观察元素大小何时在 Angular 2 中发生变化



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

模板:

<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); 
}

但这给了我一个错误:

异常:无法读取未定义的属性"本机元素">

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

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

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

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

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

最新更新