Search code examples
javascriptangulartypescriptbootstrap-modalng-bootstrap

ng-bootstrap modal open on ngOnInit()


I want to open the modal from my typescript code, that is when the component loads on the ngOnit() the modal popup should open , I don't want to create a button on the html file.

HTML:

<button class="btn btn-outline-primary mb-2 mr-2" (click)="openSm(content)">Small modal</button>

<ng-template #content let-modal>
  <div class="modal-header">
    <h4 class="modal-title">Modal title</h4>
    <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <p>One fine body&hellip;</p>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-light" (click)="modal.close('Close click')">Close</button>
  </div>
</ng-template>

Ts:

openSm(content) {
    this.modalService.open(content, { size: 'sm' });
  }

stackblitz link

I want to open the modal on ngOnit() function.


Solution

  • just use ViewChild to get the "content" and in ngOnInit call to this.open(this.content)

      @ViewChild("content",{static:true}) content:ElementRef;
    
      constructor(private modalService: NgbModal) {}
    
      ngOnInit()
      {
        this.openSm(this.content)
      }
    

    your forked stackblitz

    NOTE: I use {static:true} and put the code in ngOnInit because I imagine your "content" is always "visible", else you need use ngAfterViewInit