Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Dialog service in Angular2

In Angular 2 it seems any and all DOM manipulations are performed by components or directives. I'm used to Angular 1 however in which it was reasonably common to have certain services that created and managed their own DOM elements; most notably dialogs.

In the past it was possible to for instance create an Angular 1 service ConfirmationService with a function Confirm() that returned a Promise<bool> that showed the user a dialog to press either yes or no on, which resolved the promise.

These dialog services (for instance UI Bootstrap Modal or the NgDialog) generally work by injecting the $document, $compile and $parse services and create and inject DOM elements on the fly.

I'm having difficulties finding out what the recommended Angular 2 approach is to creating such a service. If at all possible I'd like to prevent having to create a ConfirmationComponent that has to be added to any component that needs to ask for confirmation (partly because it can also be another service that needs the confirmation and that confirmation is but one example where this is useful)

Anyway, some help/pointers would be greatly appreciated. Thanks in advance.

like image 393
Robba Avatar asked Mar 11 '23 02:03

Robba


1 Answers

If you're ok taking a dependency on sweetalert2, a dialog service becomes pretty simple:

import { Injectable } from '@angular/core';
import { default as swal } from 'sweetalert2';

@Injectable()
export class DialogService {
    confirm(title: string, message: string) {
        return swal({
            title: title,
            text: message,
            type: 'warning',
            showCancelButton: true
        });
    };
}
like image 155
Stuart Avatar answered Mar 19 '23 06:03

Stuart