Search code examples
javascripthtmlangularweb-component

Angular - Dynamic size of component not being updated


I'm using an internal private reusable component. My problem is that the width is not being dynamically updated when the viewport is updated. Here are snippets of relevant code:

component.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";
      }
    }

}

component.html

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

The width and height are supposed to change dynamically as the browser is resized, but it stays the same size as when it was rendered. If I open the modal in a specific viewport the size is always correct, it's only a problem once I am trying to resize with the modal open.

When logging the subscription to the breakpoint service, it is always correct and will log dynamically.

I've tried converting modalWidth and modalHeight to observables and using an async pipe in the html but it still has the same behaviour.

Any tips or suggestions?


Solution

  • you can inject ChangeDetectorRef in the component and after changing modalWidth, call changeDetectorRef.detectChanges() to let angular apply the change immediately to the view.

    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();
        }