/ angular

Lightweight implementation of modal dialogs for Angular

Most applications use modal dialogs as part of their UI. When building an app with Angular there are quite a lot of options when it comes to modals. Here are some of the more popular ones:

When we needed to implement modal dialogs and panels in our project at Independer, I looked at the above libraries as well as others and realized that all of them were too big and complex for what we needed.

Then I stumbled upon this little project: ngx-modal. It was quite simple and provided almost everything we needed, so I decided to copy the code and customize it our needs. I ended up changing it quite a bit, fixed a number of problems and added a few capabilities, but it still remained quite small and simple library compared to the other ones mentioned above. It served its purpose quite well on our project so I thought that it might be useful for others as well and shared the code on GitHub as well as created an NPM package.

You can find the detailed information about the library and instructions how to use it at GitHub, here I will just summarize the key features/capabilities:

  • Possibility to declare the markup of the modal as part of another component template (useful when you need a simple confirmation dialog and creating a separate component is overkill) or create a standalone component.

  • ModalService that can be injected anywhere and used to open a modal programmatically.

  • Possibility to open a modal by navigating to a route (not very common with modal dialogs, but useful with modal side-panels).

  • Comes with two sets of styles (themes):

    • independer - our own theme, useful mainly as an example;
    • bootstrap - Bootstrap 4 styles stripped down to include only what is needed to for the modals.

    Note: You don't have to use any of the above built-in themes. You can create your own from scratch or copy one of them and customize it.

  • Works with standard Bootstrap styles (e.g. from CDN).

Here are also a few code snippets to give you a general idea how to use the library:

Simple modal template:

<modal #firstModal>
    <h4>I am a Simple Dialog</h4>
    This dialog is defined inside a template of another component.
    <button class="btn btn-primary" (click)="firstModal.close()">okay!</button>

Opening a modal using ModalService:

export class HomeComponent {
  constructor(private modalService: ModalService) {

  openModal() {
    const modalRef = this.modalService.open(MyModalComponent);

    modalRef.componentInstance.myProperty = 'Modal initialization data set from HomeComponent';

    modalRef.closed.subscribe(args => {
      console.log(`Modal closed.`);

You can also try out and explore the library using this StackBlitz project: https://stackblitz.com/edit/ng-modal-playground.

Pavlo Glazkov

Pavlo Glazkov

Programmer. Full stack, with a focus on UI. JavaScript/TypeScript, Angular, Node.js, .NET

Read More