Introduction
In this article we will see how to create a modal window or dialog box in Angular. We will use Angular and typescript to show or hide the modal window.
We will be using NgbModal in order to open the modal. This is just required to create a component and pass the template in its open method.
This also have a Dismiss method for closing the modal with the particular reason.
Let’s start creating the application with the dialog service provided on a specified event.
We will modify the existing application to add the Dialog functionality.
Where to apply the modal dialog?
- We will try to show the dialog if User is clicking on “Register” button without filling the fields.
- We will try to show the dialog if the User that you are trying to register is already present.
- We will show dialog if the user is successfully created.
We will be using RXJS Subject in order to achieve the dialog service. Subject is a special type of observable that allow values to multicast to many observers.
Create a modal.service.ts in _services directory and add the below content:
- import { Injectable } from '@angular/core';
- import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
- @Injectable({
- providedIn: 'root'
- })
- export class ModalService {
- closeResult = '';
- constructor(private modalService: NgbModal){}
- open(content) {
- return this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'})
- .result.then((result) => {
- return this.closeResult = `Closed with: ${result}`;
- }, (reason) => {
- return this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
- });
- }
- private getDismissReason(reason: any): string {
- if (reason === ModalDismissReasons.ESC) {
- return 'by pressing ESC';
- } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
- return 'by clicking on a backdrop';
- } else {
- return `with: ${reason}`;
- }
- }
- }
Create dialog.service.ts in _services directory and add the below contents:
- import { Injectable } from '@angular/core';
- import { Observable, Subject } from 'rxjs';
- @Injectable({ providedIn: 'root' })
- export class DialogService {
- private dialogSubject = new Subject<any>();
- sendDialog(dialog: {type: number, message: string}) {
- this.dialogSubject.next(dialog);
- }
- clearDialog() {
- this.dialogSubject.next();
- }
- getDialog(): Observable<any> {
- return this.dialogSubject.asObservable();
- }
- }
- Create page.service.ts in _services and add below contents:
- import { Injectable } from '@angular/core';
- import { Observable, Subject } from 'rxjs';
- @Injectable({ providedIn: 'root' })
- export class PageService {
- private pageSubject = new Subject<any>();
- sendPage(dialog: {type: number, message: string}) {
- this.pageSubject.next(dialog);
- }
- clearPage() {
- this.pageSubject.next();
- }
- getPage(): Observable<any> {
- return this.pageSubject.asObservable();
- }
- }
Let’s create a component that will have the templates for opening the dialog content.
Create _component directory in app directory.
Create component prompt inside _component directory.
Open prompt.component.ts
- import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
- import { ModalService } from 'src/app/_services/modal.service';
- import { DialogService } from 'src/app/_services/dialog.service';
- import { Subscription } from 'rxjs';
- import { PageService } from 'src/app/_services/page.service';
- @Component({
- selector: 'app-prompt',
- templateUrl: './prompt.component.html',
- styleUrls: ['./prompt.component.css']
- })
- export class PromptComponent implements OnInit {
- @Input() result: number;
- subscription: Subscription;
- @ViewChild('dialog_required') dialog_required: ElementRef;
- @ViewChild('dialog_serverError') dialog_serverError: ElementRef;
- @ViewChild('dialog_success') dialog_success: ElementRef;
- closeResult = '';
- serverError = '';
- serverResponse = '';
- constructor(private modalService: ModalService, private dialogService: DialogService, private pageService: PageService) {
- this.result = 0;
- this.subscription = this.dialogService.getDialog().subscribe(dialog => {
- if (dialog) {
- this.open(dialog);
- }
- });
- }
- open(dialogType) {
- switch(dialogType.type)
- {
- case 1:
- this.modalService.open(this.dialog_required).then(data=>{
- this.closeResult = data;
- });
- break;
- case 2:
- this.serverError = dialogType.message;
- this.modalService.open(this.dialog_serverError).then(data=>{
- this.closeResult = data;
- });
- break;
- case 3:
- this.serverResponse = dialogType.message;
- this.modalService.open(this.dialog_success).then(data=>{
- this.closeResult = data;
- this.pageService.sendPage({type: 1, message: "page"})
- });
- break;
- default:
- console.log('no modal opens');
- }
- }
- ngOnInit(): void {
- console.log(this.result)
- }
- ngOnDestroy() {
- // unsubscribe to ensure no memory leaks
- this.subscription.unsubscribe();
- }
- }




Join the conversation! Your thoughts help the community grow.