Search code examples
angulartypescriptbootstrap-modal

Change NgbModal size after open


I have a modal that initially has a size, but I want the modal to change size when I change a certain value in the form.

I have this in my component .ts file that launch the modal

const modalRef = this.modalService.open(ModalFormComponent, { size : 'xl', scrollable: true });

If in the modal an information changes the modal size needs to change to lg


Solution

  • The open method of NgbModal class returns and NgbModalRef. The _windowCmptRef.instance.size property of NgbModalRef defines the size property of the currently opened Bootstrap Modal (NgbModal).

    Now the question is how to access the NgbModalRef from the popup component. One way could be to define the reference object inside a service. Like this

    import { Injectable } from '@angular/core';
    @Injectable({
      providedIn: 'root'
    })
    export class MyserviceService {
      public modalRef: any;  //modalRef will be stored in this variable
      constructor() { }
    }
    

    Now open the NgbModal like this

    this.myService.modalRef = this.ngbModalService.open(PopupComponent,  { size : 'xl', scrollable: true });
    

    In the PopupComponent, you can change the size of the modal like this

    this.myService.modalRef._windowCmptRef.instance.size='sm'; //the size property would be changed to small size.
    

    Thanks.