2

I'm working on an Angular 4 application with Bootstrap 4.

I have implemented a bootstrap modal component which works fine. On click it shows and clicking on cross closes it.

The modal contain a form to add a user.

enter image description here

And on clicking on Add User button adds the user properly.

All I want is to close the modal if users added success fully.

I used onSubmit() function in Angular component:

onSubmit({value, valid}) { if (valid) { console.log(value); this.formInvalid = false; this.userMeta = value; this.allUsers.unshift(this.userMeta); } else { console.log('Form is invalid!', valid); this.formInvalid = true; } } 

So is there any way I can close the modal in this function?

2
  • Have you included jquery in your pages? I think you would have as you are using bootstrap. Commented Oct 3, 2017 at 11:30
  • yes I have included it through .angular-cli.json file ... something like this: "../node_modules/jquery/dist/jquery.js", Commented Oct 3, 2017 at 11:50

1 Answer 1

3

Presuming you are using the project ng-bootstrap (which you should be to use bootstrap components with Angular, rather than jQuery)

In the modal component you can grab a reference to itself via dependency injection:

constructor(public modal: NgbActiveModal) { }

Then you can use the appropriate methods:

modal.dismiss() to close with an error/reason.

modal.close(something) to close with a result, your userMeta for example - whatever you want to return.


If you're using standard Bootstrap with the jQuery dependency instead of the Angular version, you should just be able to use $('#myModal').modal('hide') as described here.

Sign up to request clarification or add additional context in comments.

23 Comments

:( I wish I used ng-bootstrap ... Now I have used Standard bootstrap How can I close the modal from my typescript code?
One more question Uncle ... Can switch to ng-bootstrap?
The 2nd part of the answer explains how to do it with standard jQuery. Switching to ng-bootstrap at this point won't be too easy, you'll have to rewrite all usages of bootstrap components such as modals.
Actually second part explains how to do it with jQuery $('#myModal').modal('hide') I don't think I can use $('#myModal').modal('hide') piece of code in my TS file.
As with all external dependencies in typescript yes, try import * as $ from 'jquery' at the top of your file.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.