当模板中的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); }
但这给了我一个错误:
EXCEPTION: Cannot read property ‘nativeElement’ of undefined