all files / src/confirm/ confirm.component.ts

70.97% Statements 22/31
0% Branches 0/6
28.57% Functions 2/7
67.86% Lines 19/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                                                                                                  
import {ElementRef, Component, TemplateRef, ViewChild} from '@angular/core';
import {ConfirmService} from "./confirm.service";
 
@Component({
    selector: '[confirm]',
    template: `
        <template #template>
            <div class="modal-header">
                <button type="button" class="close" aria-label="Close" (click)="d()">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">{{title}}</h4>
            </div>
            <div class="modal-body">
                <p>{{text}}</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" (click)="c()">{{ok}}</button>
                <button type="button" class="btn btn-secondary" (click)="d()">{{cancel}}</button>
            </div>
        </template>
        <ng-content></ng-content>        
    `,
    inputs: ['ok: confirm-ok', 'cancel: confirm-cancel', 'title: confirm-title', 'text: confirm', 'confirm-if', 'confirm-settings', 'confirm-template'],
})
export class ConfirmDirective {
 
    ok: string = "Ok";
    cancel: string = "Cancel";
    title: string = "Confirm";
    text: string;
    confirmIf: boolean = true;
    confirmSettings: Object = {};
    confirmTemplate: string | TemplateRef<any> = null;
 
    @ViewChild(TemplateRef) template: TemplateRef<any>;
 
    constructor(private el: ElementRef, private confirmService: ConfirmService) {
        let element: HTMLElement = el.nativeElement;
        let oldAddEventListener: Function = element.addEventListener;
        let events: Object[] = [];
 
        function success(clickEvent) {
            events.forEach((evt: any) => {
                evt.listener(clickEvent);
            });
        }
 
        element.addEventListener("click", (event) => {
            if (this.confirmIf) {
                confirmService.confirm(this.confirmTemplate || this.template, this.confirmSettings).then(() => {
                    success(event);
                });
            } else {
                success(event);
            }
        });
 
        element.addEventListener = function(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean) {
            if (type == "click") {
                events.push({type: type, listener: listener, useCapture: useCapture});
            } else {
                oldAddEventListener(type, listener, useCapture)
            }
        };
    }
}