use*_*924 11 javascript angular
当模板中的div改变大小时,执行某些操作的最佳方法是什么?调整窗口大小时,div的大小会更改.使用Rxjs Observable/subscribe还是其他方式?
模板:
<div #eMainFrame class="main-frame">
...
</div>
Run Code Online (Sandbox Code Playgroud)
零件:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
更新的组件(此示例检测窗口大小何时更改)
constructor(ngZone: NgZone) {
window.onresize = (e) => {
ngZone.run(() => {
clearTimeout(this.timerWindowResize);
this.timerWindowResize = setTimeout(this._calculateDivSize, 100);
});
}
}
_calculateDivSize(){
console.log(this.eMainFrame.nativeElement.offsetWidth);
}
Run Code Online (Sandbox Code Playgroud)
但这给了我一个错误:
EXCEPTION:无法读取未定义的属性"nativeElement"
Gün*_*uer 11
浏览器不提供任何内容,因此您需要轮询该值
ngDoCheck()
当Angular运行更改检测时调用.我认为这是一个检查的好地方:
ngDoCheck() {
console.log(this.eMainFrame.nativeElement.offsetWidth);
}
Run Code Online (Sandbox Code Playgroud)
如果您只需要在创建组件后检查一次,请使用
ngAfterContentInit(){
// This shows the elements current size
console.log(this.eMainFrame.nativeElement.offsetWidth);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7524 次 |
最近记录: |