How to implement Angular modal in Angular 12 .?

An angular modal component is a form of temporary UI that slides into the screen, over the page content, and is often used for login/registration forms, selecting options from lists, composing messages, or presenting app configuration options for example. We can dismiss the modal manual, dismiss after a certain time lapse, or use dismiss or close method on the modal.

In this tutorial we have three goals behind this chapter. First, we will see what are different way we can use Angular modal component. Secondly, we’ll demonstrate an example of modal dialog using ngx-simple-modal and bootstrap Modal. Let’s get started.

Different options of using Angular Modal component

We can have few options of using Angular modal dialog in our application. These libraries provide modal functionality plus some of their own design. Here I have listed some popular Angular modal dialogs.

NameDescription
ngx-simple-modalIt is a library to makes modals easier in Angular, has no dependencies, but plays well with bootstrap or other frameworks. It has a size of 535 kB.
Angular Material DialogIf you are using Angular material for UI, then it is the best approach to used Angular material Dialog.
ng-bootstrap modalIf you are using Twitter bootstrap UI for your project, then it is best to approach use the bootstrap modal using ng-bootstrap.

Setting up and configure Angular Modal dialog project.

Let first create our modal project and we’ll demonstrate two examples of the modal. Before starting an angular project you need to install nodejs and Angular CLI in your system.

ng new modalApp

Angular modal dialog using ngx-simple-modal

We’ll demonstrate modal dialog using third-party library ngx-simple-modal. Here we first need to install this library in our project by following the command.

npm i ngx-simple-modal --save

Here is a screenshot of our first example of a modal component

Angular modal dialog example

Install ngx-simple-modal and create modal component

Once we have created our modal project, let us know to install and create a modal component by running the following command.

npm i ngx-simple-modal --save
ng g component components/modal/basic

The above command will install our modal component and it will create modal component basic inside folder app/components/modal/basic. The ngx-simple-modal library provides the following features.

  • Create clear and reusable modal components.
  • It makes managing modals painless and clearer.
  • Draggable modals – Our above example is draggable modal component.
  • Extend the ModalComponent class and implement any content you want.

Import Simple modal module

To use the ngx-simple-modal library we need to import the Simple module inside our application. We can import this module into the application in either the root module or anyone module where we want to use it. In our case let at this module at root module i.e the app.module.ts file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { defaultSimpleModalOptions, SimpleModalModule } from 'ngx-simple-modal';
import { BasicComponent } from './components/modal/basic/basic.component';

@NgModule({
  declarations: [
    AppComponent,
    BasicComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    SimpleModalModule.forRoot({ container: 'modal-container' }, {
      ...defaultSimpleModalOptions, ...{
        closeOnEscape: true,
        closeOnClickOutside: true,
        wrapperDefaultClasses: 'o-modal o-modal--fade',
        wrapperClass: 'o-modal--fade-in',
        animationDuration: 300,
        autoFocus: true,
        draggable: true
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the app module, we can simply import SimpleModule, but we need to use the draggable feature of SimpleModule. An optional second parameter takes a global object of type SimpleModalOptions (all fields required).

To use SimpleModule style, then we can import its style, which is optional and its CSS already provides a transparency overlay, opacity, and slide animation. If you are using scss file like me then import it scss file in style.scss as follows.

@import '../node_modules/ngx-simple-modal/styles/simple-modal.scss';

If you are using CSS for your component style, then inside your angular-cli.json update your styles sections to include our CSS

"styles": [
  "styles.css",
  "../node_modules/ngx-simple-modal/styles/simple-modal.css"
],

Angular modal dialog example

Now we had complete all configurations for SimpleModal, let now add a button in the app component template to open modal.

<div class="container">
  <button type="button" class="btn btn-primary" (click)="basicModal()">
   Basic Modal
  </button>
  <router-outlet></router-outlet>
</div>

Let open our basic modal, and pass data from our component to the calling modal and edit the app.component.ts file.

import { Component } from '@angular/core';
import { SimpleModalService } from 'ngx-simple-modal';
import { BasicComponent } from './components/modal/basic/basic.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  constructor(
    private SimpleModalService: SimpleModalService
  ) { }

  basicModal(): void {
    this.SimpleModalService.addModal(BasicComponent, {
      title: 'Hi All! : From Edupala',
      message: 'Believing in your dreams is the only way to reach your destination. '
    }, {
      draggable: true
    }).subscribe((isConfirmed) => {
      //We get modal result
      if (isConfirmed) {
        alert('accepted');
      }
      else {
        alert('declined');
      }
    });
  }
}

We have to import and inject simpleModalService inside our constructor. We can pass data to our modal, and in modal objects, we have to pass what modal we are calling. In our case, BasicComponent is our modal and we want to pass title and message string data to modal.

Modal component and retrieve data

Once we click on the basic modal button, it will open our basic modal. In basic modal, we can display data we received from our component. In ngx-simple-modal we have different options to implement modal, we are using AlertModel and you can check more options on the ngx-simple-modal site.

Let edit the basic.component.ts file to implement the AlertModal example.

import { Component} from '@angular/core';
import { SimpleModalComponent } from 'ngx-simple-modal';

export interface AlertModel {
  title?: string;
  message: string;
}
@Component({
  selector: 'app-basic',
  templateUrl: './basic.component.html',
  styleUrls: ['./basic.component.scss']
})
export class BasicComponent extends SimpleModalComponent<AlertModel, null> implements AlertModel {
  title: string = '';
  message: string = '';
  constructor() {
    super();
  }

  confirm() {
    this.close();
  }

}

Let edit our basic modal template to display our data and button to dismiss the modal.

<div class="modal-content">
    <div class="modal-header">
        <h4>{{ title || 'Default title.'}}</h4>
    </div>
    <div class="modal-body">
        <p>{{ message || 'Default modal message.'}}</p>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-outline-danger" (click)="close()">
          Cancel
        </button>
        <button type="button" class="btn btn-primary" (click)="confirm()">     
         OK
        </button>
    </div>
</div>

How to apply Angular modal header and footer background color

Angular modal dialog
Angular modal component

We can see that we had applied background color to the header and footer of the modal. Let add background color in style.scss file.

/* You can add global styles to this file, and also import other style files */
@import '../node_modules/ngx-simple-modal/styles/simple-modal.scss';

  .modal-content {
    max-width: 400px;
  }
  
  .modal-content-size-m {
    max-width: 992px;
  }
  
  .modal-content-size-l {
    max-width: 1200px;
  }
  
  .modal-footer, .modal-header {
    height: 56px;
    padding: 0 16px;
  }
  
  .modal-header {
    background-color: #cecece;
    border-bottom: 1px solid #cecece;
  }
  
  .modal-body {
    padding: 16px;
  }
  
  .modal-footer {
    background-color: #ee6060;
    border-top: 1px solid #ee6060;
  }
  
  .btn:hover {
    background: #3cb0fd;
    text-decoration: none;
  }

We have aligned our basic modal at the center of our page, this can be achieved by applying the following CSS style on the host element of the basic components. Edit basic.component.scss file as follow.

:host {
    top: -200px;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
}

Angular modal dialog using bootstrap

Here we will demonstrate the second example, using the ng-bootstrap library. This library has lots of bootstrap components built specifically for Angular and it doesn’t have a dependency on bootstrap javascript and jquery.

Here is a screenshot of our Angular bootstrap modal

Angular bootstrap modal

We had articles on how to install and configure ng-bootstrap in our Angular project. If you want to know then you check on it. Let create a bootstrap basic modal component and install the ng-bootstrap library by running the following command.

ng add @ng-bootstrap/ng-bootstrap
ng g component components/modal

Here we only demonstrate basic modal for displaying modal using bootstrap. Let edit the app.component.ts file to open are basic modal.

import { Component } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from './components/modal/modal.component';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  constructor(private modalService: NgbModal) { }

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

Edit the app.component.html template to add a /button to call method to open modal.

<div class="container">
  <h1>Ng Bootstrap Modal</h1>
  <p>
    Modal is a form of temporary UI that slides into the screen, over the page content, and is often used for
    login/registration forms, composing messages, or presenting app configuration options etc.
  </p>
  <button class="btn btn-primary" (click)="openModal()">Show Dialog</button>
</div>

<router-outlet></router-outlet>

Ng bootstrap modal design

In our bootstrap basic modal, we had applied background color to the modal header and footer. Let edit the modal.component.ts file

import { Component, OnInit } from '@angular/core';
import { NgbModal, ModalDismissReasons, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss']
})
export class ModalComponent implements OnInit {
  closeResult = '';

  constructor(
    public activeModal: NgbActiveModal
  ) { }

  ngOnInit(): void {
    throw new Error('Method not implemented.');
  }
}

In our modal component template, we have a header, modal content, and footer. Let add this in the modal component template.

<div class="modal-header bg-info">
    <h4 class="modal-title">HI From Edupala</h4>
    <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
<div class="modal-body">
    <p>Believing in your dreams is the only way to reach your destination.</p>
</div>
<div class="modal-footer bg-info">
    <h6>Boostrap basic modal example</h6>
</div>

Conclusion
We complete our Angular modal component tutorial, we have demonstrated two examples of the modal components. I hope you have got some idea on how to use modal in Angular project.

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top