Search code examples
htmlangulartypescriptng2-bootstrap

How to close an Angular2 modal with a boolean?


I'm new to html and Angular2. Any help with this problem would be much appreciated.

I am placing a form component inside a ng2-modal and I would like the modal to close when the form returns a boolean from an event.

The form is for adding a new class to a database. Its first usage is on another page where it is not inside a modal. There, upon clicking cancel/submit in the component, I have it return true and then redirect to another url.

For the new implementation I want the modal to close when the form returns true. The problem is that the save/cancel buttons are in the component containing the form. So I can't just use the modal's click event to close it.

Here is my current code:

<modal #addNewClassModal>
    <modal-header>
        <h4 class="modal-title"><i class="fa fa-cube"></i>  Add a new class</h4>
    </modal-header>
    <modal-content>

      <div>
        <add-new-class (closeModal)="finishAddingNewClass($event)">
        </add-new-class>
      </div>

    </modal-content>
</modal>

My problem is that I can't figure out how to get the modals close() method to rely on the boolean. I've tried putting closeModal="addNewClassModal.close()" in different places and switching around the syntax but its not working and I can't find anything online.


Solution

  • You can pass a reference to addNewClassModal to your AddNewClass component:

    <add-new-class [modal]="addNewClassModal">
    </add-new-class>
    

    And in your AddNewClass component add Input() for modal:

    import { Input } from '@angular/core';
    import { ModalDirective } from 'ng2-bootstrap/components/modal';
    
    @Input()
    modal: ModalDirective; // you can also set type to any instead of ModalDirective
    

    Then in your component you can close modal with hide() function:

    this.modal.hide();