Skip to content Skip to sidebar Skip to footer

How To Open A Bootstrap 5 Modal Which Is In Child From A Button Click Which Is In Parent , Without Installing Ng Bootstrap In Angular

I have a button in parent component, upon clicking it I want to open a modal which is in child component. I am using bootstrap 5 in my project. I don't want to install ngx-bootstra

Solution 1:

futhermore to install bootstrap, install @types/bootstrap

npm install --save@types/bootstrap

Then you can control a Modal using typeScript. E.g.

<!--in the button I use template reference--><buttontype="button"class="btn btn-primary" (click)="show(modal)">
    Launch demo modal
  </button><!--see the template reference--><div #modalclass="modal fade"tabindex="-1" ><divclass="modal-dialog"><divclass="modal-content"><divclass="modal-header"><h5class="modal-title"id="exampleModalLabel">Modal title</h5><buttontype="button"class="btn-close"data-bs-dismiss="modal"aria-label="Close"></button></div><divclass="modal-body">
          ...
        </div><divclass="modal-footer"><buttontype="button"class="btn btn-secondary"data-bs-dismiss="modal">Close</button><buttontype="button"class="btn btn-primary">Save changes</button></div></div></div></div>

And in .ts

import {Modal} from'bootstrap'//<--import Modalshow(modalElement){
    const modal=newModal(modalElement);
    modal.show();
  }

Or using ViewChild

@ViewChild('modal') modalRef
  show(){
    //see that using ViewChildren you use nativeElementconst modal=newModal(this.modalRef.nativeElement);
    modal.show();
  }

As your child is who has the modal, use a template reference variable in children (e.g. #modal) so you parent can be

  <button type="button" (click)="show(child.modal)">
    Launch demo modal
  </button>
  <child #child></child>//in this case we need use "nativElement"show(modalRef){
    const modal=newModal(modalRef.nativeElement);
    modal.show();
  }

stackblitz

Post a Comment for "How To Open A Bootstrap 5 Modal Which Is In Child From A Button Click Which Is In Parent , Without Installing Ng Bootstrap In Angular"