Naftis Naftis -4 years ago 472
TypeScript Question

Angular2 modal confirmation dialog via DI not shown


I'm trying to use a simple confirmation modal for my angular2 app by adapting the code found at to use Bootstrap styles rather than material design.

I like the idea behind this confirmation dialog, because it is simple and Angular2-oriented: you just inject a service in your component to be able to invoke the confirmation dialog, and get the result back via a promise. The service is just:

export class ConfirmService {
public activate: (message?: string, title?: string) => Promise<boolean>;

The confirmation dialog is used through this service. When injected in the confirm component, the
function of this service is bound to the corresponding function in that component. The component is in charge of manipulating the DOM to show the dialog and get the result back (via a Promise).

Here is the component's constructor:

constructor(confirmService: ConfirmService) {
confirmService.activate = this.activate.bind(this);

This way, we must only:

  1. add the component to the root app component's template, so that it can be used throughout the components tree.

  2. inject this service to use it anywhere.

Now this seems to work and debugging I can see that the bound component's function is invoked, and the DOM elements references (got via
, as in the original code as I tried to minimize my changes; I suppose using a bound
property would be preferable) are not null. Yet, the dialog is not shown when its
is set to 1, nor any error appears in the console. You can easily see it in the Plunker quoted at the top of this post. Any suggestion?

Answer Source

So, the actual issue here, from what I can tell with the plunker you provided, is that you aren't changing the display value of the element's style from none to one where it will display.

To do so, add this line to the end of your show function: = 'block';

Plunker forked from yours:

As a suggestion, you can use ViewChild and ElementRef along with template variable naming to make things a little more strongly typed and ditch your ngOnInit assignments.

<div #myModal>
@ViewChild('myModal') _confirmElement: ElementRef;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download