为什么容器大小设置在ngOnInit上不起作用?

我使用以下命令来设置容器的大小:

ngOnInit() {

this.innerWidth = document.getElementById("Cont").clientWidth;
this.containerWidth = this.innerWidth;
console.log("init");
}

@HostListener('window:resize',['$event'])
onResize(event) {

this.innerWidth = document.getElementById("Cont").clientWidth;
this.containerWidth = this.innerWidth;
}

当我加载页面时,容器比窗口​​大,因此我必须滚动,在窗口调整大小后,一切都按预期工作,不再需要滚动。有趣的是,我在控制台中看到他的消息“ init”,这意味着代码已执行。

为什么容器在init上没有大小?

谢谢!

wkz123456 回答:为什么容器大小设置在ngOnInit上不起作用?

我认为您需要使用CSS进行管理。但是,如果您需要使用选择器访问dom元素,请使用ngAfterViewInit生命周期挂钩。

尝试一下。

ngAfterViewInit() {
     this.innerWidth = document.getElementById("Cont").clientWidth;
     this.containerWidth = this.innerWidth;
  } 

希望它能帮助您!

本文链接:https://www.f2er.com/3042017.html

大家都在问