Angular 2 Modal Dialog
- What is Modal Dialog in Angular 2
- Import the Libraries to Create a Modal Dialog in Angular 2
- Modal Service to Create a Modal Dialog in Angular 2
- Custom Modal Component to Create a Modal Dialog in Angular 2
Angular 2.0 is the latest version of the popular JavaScript framework. It provides developers with a new component-based architecture, supports mobile devices, and is written in TypeScript.
Modal dialogs are windows that pop up on top of the current window and block interaction until closed. This article will explain the Angular 2.0 modal dialog in detail.
What is Modal Dialog in Angular 2
To help developers create more dynamic and interactive web applications, Angular 2.0 introduced a new component called Modal Dialog
.
The terms modal dialog
and modal window
may appear to be confusing, but they are not. Most people refer to a modal window
as a popup by default.
The modal dialog
enables developers to create a variety of dialogs with rich content and animations. It can be used in different ways, for example:
- To prompt the user by asking for input.
- To show important messages or notifications.
- To display error messages or confirmation messages.
Click here if you want to learn more about Modal Dialog.
Let’s divide our work into the following for simplicity.
- Add the Libraries
- Modal Services
- Modal Component
For styling purposes, we used Bootstrap.
Import the Libraries to Create a Modal Dialog in Angular 2
Import the following libraries in the index.html
file to enhance the functionality of your code.
<script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://npmcdn.com/zone.js@0.6.12?main=browser"></script>
<script src="https://npmcdn.com/reflect-metadata@0.1.3"></script>
<script src="https://npmcdn.com/systemjs@0.19.27/dist/system.src.js"></script>
After this, our main concern is to compile the code. You can’t directly compile stuff to the DOM with Angular 2; you need a placeholder.
That’s why we made a modal placeholder. Keep in mind this is the most important step to take a start.
@Component({
selector: "modal-placeholder",
template: `<div #modalplaceholder></div>`
})
export class ModalPlaceholderComponent implements OnInit {
@ViewChild("modalplaceholder", {read: ViewContainerRef}) viewContainerRef;
Modal Service to Create a Modal Dialog in Angular 2
We are heading towards the second step, also called the root step. The main purpose of modal service
is to make it easier for on-page and modal components to communicate.
Modal service also keeps track of which on-page modals are available and how to interact with them.
import {Component,NgModule, ViewChild, OnInit, ViewContainerRef, Compiler, ReflectiveInjector, Injectable, Injector, ComponentRef} from "@angular/core";
import {Observable, Subject, BehaviorSubject, ReplaySubject} from "rxjs/Rx";
@Injectable()
export class ModalService {
private vcRef: ViewContainerRef;
private injector: Injector;
public activeInstances: number;
constructor(private compiler: Compiler) {
}
registerViewContainerRef(vcRef: ViewContainerRef): void {
this.vcRef = vcRef;
}
registerInjector(injector: Injector): void {
this.injector = injector;
}
create<T>(module: any, component: any, parameters?: Object): Observable<ComponentRef<T>> {
let componentRef$ = new ReplaySubject();
this.compiler.compileModuleAndAllComponentsAsync(module)
.then(factory => {
let componentFactory = factory.componentFactories.filter(item => item.componentType === component)[0];
const childInjector = ReflectiveInjector.resolveAndCreate([], this.injector);
let componentRef = this.vcRef.createComponent(componentFactory, 0, childInjector);
Object.assign(componentRef.instance, parameters);
this.activeInstances ++;
componentRef.instance["com"] = this.activeInstances;
componentRef.instance["destroy"] = () => {
this.activeInstances --;
componentRef.destroy();
};
componentRef$.next(componentRef);
componentRef$.complete();
});
return <Observable<ComponentRef<T>>> componentRef$.asObservable();
}
}
@Component({
selector: "modal-placeholder",
template: `<div #modalplaceholder></div>`
})
export class ModalPlaceholderComponent implements OnInit {
@ViewChild("modalplaceholder", {read: ViewContainerRef}) viewContainerRef;
constructor(private modalService: ModalService, private injector: Injector) {
}
ngOnInit(): void {
this.modalService.registerViewContainerRef(this.viewContainerRef);
this.modalService.registerInjector(this.injector);
}
}
@NgModule({
declarations: [ModalPlaceholderComponent],
exports: [ModalPlaceholderComponent],
providers: [ModalService]
})
export class ModalModule {
}
export class ModalContainer {
destroy: Function;
componentIndex: number;
closeModal(): void {
this.destroy();
}
}
export function Modal() {
return function (world) {
Object.assign(world.prototype, ModalContainer.prototype);
};
}
What is RxJS
?
RxJS
(Reactive Extensions for JavaScript) is a suite of modules that allow you to create asynchronous and event-based programs in JavaScript utilizing visible arrays and composition.
Custom Modal Component to Create a Modal Dialog in Angular 2
The custom modal directive can add modals in an Angular application using the <modal>
tag.
When a modal instance loads, it registers with the ModalService
so that the service can open and dismiss modal windows. It deregisters from the ModalService
when destroyed using the Destroy
method.
import {Modal} from "./modal.module";
import {Component} from "@angular/core";
@Component({
selector: "my-cust",
template: `
<h1>Basic Components of a Car</h1>
<button (click)="onDelete()">×</button>
<ul>
<li *ngFor="let option of options">{{option}}</li>
</ul>
<div>
<button (click)="onDelete()">
<span>Delete</span>
</button>
<button (click)="onSave()">
<span>Save</span>
</button>
</div>
`
})
@Modal()
export class ModalComponent {
ok: Function;
destroy: Function;
closeModal: Function;
options = ["Speed", "Mileage", "Color"];
onDelete(): void{
this.closeModal();
this.destroy();
}
onSave(): void{
this.closeModal();
this.destroy();
this.ok(this.options);
}
}
Finally, the index.html
code is given below.
<!DOCTYPE html>
<html>
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://npmcdn.com/zone.js@0.6.12?main=browser"></script>
<script src="https://npmcdn.com/reflect-metadata@0.1.3"></script>
<script src="https://npmcdn.com/systemjs@0.19.27/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-hoop>Loading...</my-hoop>
</body>
</html>
So, this is the way to create a modal in Angular 2. The code is maintainable, flexible, and easy to use. Click here to check the live demonstration of the code.
Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.
Facebook