eestein eestein - 4 days ago 5
AngularJS Question

How can I open a modal component programmatically?

I'd like to open a modal programmatically like a modal service. This is how I did it in angular 1 :

uibModal.open({template:'url.html', controller: MyController})
that way I wouldn't need to add modal HTML code to my parent screen.

Let's say I have this folder structure:

components
-- screen1
---- parent.component.ts
-- modal1
---- modal1.component.ts
---- modal1.template.html
-- modal2
---- modal2.component.ts
---- modal2.template.html


then on
parent.component.ts
I'd like to open
modal1


But since the modal I'm opening is dynamic I'd like it to open like a service (or anything similar). So I'm passing the information to my
parent.component
of which modal it should open, and then using a modal service (like in angular1) it opens the modal.

How can I approach this?

Thanks!

Answer

You can use angular-ui/bootstrap port to Angular 2 which has a service equivalent to uibModal: https://ng-bootstrap.github.io/#/components/modal

Its usage is equivalent to the Angular 1.x version - you just call the open() method on a service! Here is an example:

export class NgbdModalComponent {
  constructor(private modalService: NgbModal) {}

  open() {
    const modalRef = this.modalService.open(NgbdModalContent);
  }
}

Here is a live example: http://plnkr.co/edit/4pgz0My5Mnt4VoAkIsPa?p=preview

Comments