22

I want user click the Submit button and the modal close automatically.

If I add data-dismiss="modal" in the Submit <button>, it won't run submitComments().

I tried to do something like $('#myModal').modal('hide');, but not succeed.

So how can I close a modal in Angular 2? Thanks

<button type="button" class="btn btn-info" data-toggle="modal" data-target="#myModal">Open Modal</button>

<div id="myModal" class="modal fade">
     <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <form (ngSubmit)="submitComments()">
                    <div class="form-group row">
                        <label class="form-control-label col-sm-2">Comments:</label>
                        <div class="col-sm-10">
                            <textarea class="form-control" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-default">Submit</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

.

submitComments() {
    // I want to do something like $('#myModal').modal('hide'); here.
}
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267

10 Answers10

34

Using @ViewChild

add #closeBtn to the element with data-dismiss="modal"

<a><i class="fa fa-close" data-dismiss="modal" #closeBtn></i></a>

Component html

<div class="modal fade" id="yourModalId">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <a><i class="fa fa-close" data-dismiss="modal" #closeBtn></i></a>
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
      </div>
    </div>
  </div>
</div>

using this.closeBtn.nativeElement.click(); to trigger click event will close your modal.

Component typescript

import {ViewChild, ElementRef} from '@angular/core';
@Component({
    moduleId: ...,
    selector: '.',
    templateUrl: '.',
    styleUrls: ['.']
})
export class yourClass {
    @ViewChild('closeBtn') closeBtn: ElementRef;

    yourFunction() {
        //do something
        ...
        ...
        //close your modal
        this.closeModal();
    }

    //call this wherever you want to close modal
    private closeModal(): void {
        this.closeBtn.nativeElement.click();
    }
}
Siegen
  • 943
  • 10
  • 13
31

You can do it by simply declaring jQuery variable with any type inside Angular2 controller.

declare var jQuery:any;

Add this just after import statements and before component decorator.

Then access bootstrap modal with it's id like this.

jQuery("#myModal").modal("hide");
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
Devesh Jadon
  • 7,004
  • 4
  • 22
  • 27
19

Apart from the @MattScarpino's answer, another alternative is just to change your button type to button from submit and call your function submitComments() and at the same time call dismiss-modal. by doing so you are able to dismiss the modal and call function too at the same time hope this may help you. here is example:

<button type="button" class="btn btn-info" data-toggle="modal" data-target="#myModal">Open Modal</button>

<div id="myModal" class="modal fade">
     <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <form>
                    <div class="form-group row">
                        <label class="form-control-label col-sm-2">Comments:</label>
                        <div class="col-sm-10">
                            <textarea class="form-control" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="button" (click)='submitComments()' data-dismiss="myModal" class="btn btn-default">Submit</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

#Update

if you wish to close modal from your controller side you can use using this way

$("#myModal").modal("hide");
Vel
  • 9,027
  • 6
  • 34
  • 66
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • hey @HongboMiao seems you are working with forms of angular2, i would like if you answer here if you know the exact answer. http://stackoverflow.com/q/34350049/5043867 – Pardeep Jain Feb 13 '16 at 06:32
  • sorry i cannot really help, I am also new. I just uses some ngModel with together – Hongbo Miao Feb 13 '16 at 21:51
  • ohh its okay :) for more info about form i have posted this new question hope this will help you to learn something new. http://stackoverflow.com/q/35383765/5043867 – Pardeep Jain Feb 14 '16 at 03:21
  • 1
    Awesome answer, I was in the same boat and I was using data-dismiss just like this but my action was (submit) on the button, not (click), changing it like you suggest resolved it. Thanks! – continuousqa Dec 11 '16 at 18:55
  • How to close it only after success from Http POST method? if post give error I don't want to close it – Dinkar Thakur Jan 20 '17 at 05:49
  • What is `dismiss-modal` ?? You never define what that is. – AlxVallejo Feb 18 '23 at 00:56
4

First, set the div's hidden property equal to a variable:

<div id="myModal" [hidden]="hideModal" class="modal fade">

Second, in the class, define a boolean named hideModal and set it to false:

hideModal: boolean = false;

Third, in submitComments(), set hideModal to true.

Niraj
  • 602
  • 2
  • 7
  • 12
MatthewScarpino
  • 5,672
  • 5
  • 33
  • 47
4

Perfect answer in this universe.........................

step 1 : give unique id to the dismiss button of modal

step 2 : after successfully submitted form or finishing task call

document.getElementById("addProductCloseButton").click();

in your class

Abdul Rasheed
  • 6,486
  • 4
  • 32
  • 48
  • 3
    This is not a good solution. You should rarely, if ever, have to reach directly into the DOM to accomplish an Angular task. This is a good example of bad loose coupling. – Taylor Hill Sep 11 '17 at 16:59
  • I spent a lot of time, after submitting button how to close the modal. finally, I got. Thank you @pravash – Senthil Jan 09 '18 at 11:06
  • No answer is working in my case. Even though it is not the correct way to do it, I will prefer this. Not a single answer working for me and found no documentation on it. Thanks @Pravash – Suresh Kamrushi Feb 12 '18 at 11:46
3

i use one of the answer and with some edit its work perfectly for me, i hope it can help for try it change "yourmodal" to modal name that is your target you should use button Instead of i

<button hidden="hidden" class="fa fa-close" data-dismiss="modal" id="closeBtn" #closeBtn (click)="yourModal.close()"></button>

Component html

<div style="margin-top: 0px !important;">
    <button type="button" id="openModal" #openModal class="btn btn-fab-mini btn-outline-primary" style="float:right" (click)="yourModal.open()"><strong>click here to open modal</strong></button>
    <modal #yourModal>
      <ng-template #modalHeader>
       <button hidden="hidden" class="fa fa-close" data-dismiss="modal" id="closeBtn" #closeBtn (click)="yourModal.close()"></button>
      </ng-template>
      <ng-template #modalBody>
        <yourmodalSelectorname></yourmodalSelectorname>
      </ng-template>
      <ng-template #modalFooter></ng-template>
    </modal>
  </div>

TypeScript

import {ViewChild, ElementRef} from '@angular/core';

@Component({
moduleId: ...,
selector: '.',
templateUrl: '.',
styleUrls: ['.']})



yourFunction() {
    //do something
    ...
    ...
    //close your modal
    this.closeModal();
}

//call this wherever you want to close modal
private closeModal(): void {
    this.closeBtn.nativeElement.click();
}
Mehrdad
  • 61
  • 1
  • 4
2

Try not to include the form in your modal body instead add two buttons for the same in your footer section.

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span aria-hidden="true">&times;</span></button>
          </div>
          <div class="modal-body">
    <label class="form-control-label col-sm-2">Comments:</label>
                    <div class="col-sm-10">
                        <textarea class="form-control" rows="3"></textarea>
                    </div>
          </div>
          <div class="modal-footer">
            <button class="btn btn-default" data-dismiss="modal" aria-hidden="true">Close</button>
            <button type="submit" class="btn btn-primary" >Save changes</button>
          </div>
        </div>
      </div>
    </div>
Marilynn
  • 71
  • 5
0

I have got a better solution. when you open your modal, save the modal reference :

this.modalRef = this.modalService.open()

and then when you need to close the modal simply :

this.modalRef.close()
hymenoby
  • 1
  • 2
0

this is the easy step to close popup modal in angular in you component.ts file include these line

 import '../../../assets/js/custom.js';
 declare var closepopup:any;

the custome file path depend on your directory stracture

in custome file include this funnction

 function closepopup()
 {
  $(".modal").modal('hide');
 }

after this if you have condition on form validion event form data validated then you want to close popup modal then include this line

closepopup();

if you still facing issue then inform me i will be there for you

abubakkar tahir
  • 737
  • 1
  • 11
  • 13
-1

Just declare an id = "close_model" in dismiss button and put this code in the function where you want to close the model ::

window.document.getElementById("close_model").click() ;