【问题标题】:Why does the container size setting not working on ngOnInit?为什么容器大小设置在 ngOnInit 上不起作用?
【发布时间】:2020-03-19 21:49:51
【问题描述】:

我使用这个命令来设置容器的大小:

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”这应该意味着代码已执行。

为什么容器的大小不是 onInit?

谢谢!

【问题讨论】:

  • 我可能认为这是因为视图还不稳定。你在 ngOnit 之后渲染一些东西吗?
  • 感谢您的回复拖!我发现了问题,在 ngOnInit 中确实有另一个命令干扰了主命令...
  • 很高兴知道问题已修复!祝你好运!
  • @Drag13 您可以发布答案以便 OP 接受并投票吗? meta.stackoverflow.com/questions/294791/…
  • @Plochie 实际上我没有给出正确答案 - 只是一些建议检查

标签: angular events event-listener ngoninit


【解决方案1】:

我认为您需要使用 CSS 来管理它。但是如果你需要使用选择器访问 dom 元素,那么请使用 ngAfterViewInit 生命周期钩子。

试试这个。

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

希望对你有帮助!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多