首页 > 解决方案 > Angular - 组件的动态大小未更新

问题描述

我正在使用内部私有可重用组件。我的问题是当视口更新时宽度没有动态更新。以下是相关代码片段:

组件.ts

export class Component {
    modalWidth: string | undefined;
    
    ngOnInit() {
        this.breakpointServiceSubscription$ = this.breakpointService.breakpoint$.subscribe(() => {
           if (this.breakpointService.isSmall()) {
               console.log("small")
               this.modalWidth = "50px";
           }
           else {
               this.modalWidth = "500px";
      }
    }

}

组件.html

<modal [width]="modalWidth">...</modal>

当浏览器调整大小时,宽度和高度应该动态变化,但它保持与渲染时相同的大小。如果我在特定视口中打开模态,则大小总是正确的,只有在我尝试在打开模态的情况下调整大小时才会出现问题。

将订阅记录到断点服务时,它始终是正确的,并且会动态记录。

我尝试将 modalWidth 和 modalHeight 转换为 observables 并在 html 中使用异步管道,但它仍然具有相同的行为。

有什么提示或建议吗?

标签: javascripthtmlangularweb-component

解决方案


您可以注入ChangeDetectorRef组件并在更改 modalWidth 后调用changeDetectorRef.detectChanges()以让 Angular 立即将更改应用到视图。

constructor(private cdr: ChangeDetectorRef) {}

 ngOnInit() {
        this.breakpointServiceSubscription$ = this.breakpointService.breakpoint$.subscribe(() => {
           if (this.breakpointService.isSmall()) {
               console.log("small")
               this.modalWidth = "50px";
           }
           else {
               this.modalWidth = "500px";
      }
      // apply change immediately
      this.cdr.detectChanges();
    }

推荐阅读