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.

modal/modal.service.ts

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

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

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

We can now associate our modal markup for this

modal/modal.component.html

<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>
    </div>
</div>

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

modal/modal.component.scss

.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

test/test.component.ts

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

@Component({
    selector: 'test-component',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.scss']
})

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

    openModal() {
        this.modalService.open();
    }
}

Then inside of our markup we can add our code

test/test.component.html

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

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