Naftis Naftis - 1 month ago 15
TypeScript Question

Angular2 modal confirmation dialog via DI not shown

Repro: http://plnkr.co/edit/YLOf2BLMi93Jg5yOgA96

I'm trying to use a simple confirmation modal for my angular2 app by adapting the code found at http://koscielniak.me/post/2016/03/angular2-confirm-dialog-component/ 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
activate
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
document.getElementById
, as in the original code as I tried to minimize my changes; I suppose using a bound
@ViewChild
property would be preferable) are not null. Yet, the dialog is not shown when its
opacity
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

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:

    this._confirmElement.style.display = 'block';

Plunker forked from yours: http://plnkr.co/edit/b3inbVhKK5PzV6NdQngq?p=preview

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;