【发布时间】: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”
【问题讨论】:
-
你试过
element.resize吗?这可能会有所帮助:*.com/questions/21170607/…
标签: javascript angular