I'm streaming

Angular 2 reusable modal service

I was recently working on an Angular 2 project that required a modal to be displayed to the end user. I decided to build a reusable component / service that can be injected into any other component and can manage the state of the modal.

To do so, I created a service that will control both the showing and hiding of the modal, as well as the current state.


import {Injectable} from '@angular/core';
import { Subject } from 'rxjs';

export class ModalService {
    isShowing = false;
    modal = new Subject();

    getModal() {
        return this.modal;
    open() {
        this.isShowing = true;
    close() {
        this.isShowing = false;
    closeModal() {

We can now associate our modal markup for this


<div class="fade in modal" [ngClass]="{'modal-open': modalOpen}">
    <div class="modal-dialog">
        Modal content and things
        <button class="btn btn-primary" (click)="closeModal($event)">Close</button>

Now to actually make the modal work, we need to add our styles to work with our ngClass


.modal {
  display: none;
  position: absolute;
  margin-top: 50%;
  top: -25%;
  right: 0;
  bottom: 0;
  left: 0;
  &-open {
    display: block;

Inside of our desired components typescript file we can add now interact with our newly created service


import { Component } from '@angular/core';
import { ModalService } from "../modal/modal.service";

    selector: 'test-component',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.scss']

export class TestComponent {
    constructor(private modalService: ModalService) {}

    openModal() {

Then inside of our markup we can add our code


<div class="row">
    <button (click)="openModal()">Open!</button>

An inventive, entrepreneurial and positively unsatisfied mind that constantly pushes the tech boundaries to create new solutions and devices that change people’s lives.

Leave a Reply