Best practice for calling the NgbModal open method

You can now do the following...

Lets say you have a model component Confirm model that you want to use it in any other component.

  1. ModelComponentName is added to the declarations and entryComponent sections in the module.ts
  2. Dont forget to add NgbModule.forRoot() in the imports of your module file which contains the declarations you mentioned above.
  3. Ensure that your model component template is inside div tag and not the ng-template tag.

You can then use the following open method from any other component.

modalReference: NgbModalRef;
constructor(private modalService: NgbModal) { }
this.modalReference = this.modalService.open(ModelComponentName, {backdrop: 'static',size: 'lg', keyboard: false, centered: true});

As of today the open method of https://ng-bootstrap.github.io/#/components/modal has the following signature: open(content: string | TemplateRef<any>, options: NgbModalOptions). As you can see from this signature you can open a modal providing content as:

  • string
  • TemplateRef

The string-typed argument is not very interesting - in fact it was mostly added to aid debugging / unit-testing. By using it you can pass just ... well, a piece of text , without any markup not Angular directives. As such it is really a debug tool and not something that is useful in real-life scenarios.

The TemplateRef argument is more interesting as it allows you to pass markup + directives to be displayed. You can get a hand on a TemplateRef by doing <template #refVar>...content goes here...</template> somewhere in your component template (a template of a component from which you plan to open a modal). As such the TemplateRef argument is powerful as it allows you to have markup, directives, other components etc. The downside is that TemplateRef is useful only if you are opening a modal from a component with a template.

I've got an impression that you are looking for the feature that is planned but not implemented yet - ability to open a modal with a component type as content. It would work as follows: modalService.open(MyComponentWithContent). As I've mentioned this is part of the roadmap but not implemented yet. You can track this feature by following https://github.com/ng-bootstrap/ng-bootstrap/issues/680