angularangular-directivejquery-confirm

Angular 4 Confirm Directive


I'm trying to create a directive for jQuery Confirm in Angular 4. However, I'm having a hard time stopping binded events happening. Here is my structure:

menus.component.html:

<a (click)="delete(menu)" class="btn" confirm><i class="icon-trash"></i></a>

menus.component.ts:

delete(menu: Menu): void {
    this.menuService.delete(menu.id)
        .subscribe(
            error =>  this.errorMessage = <any>error);
}

confirm.directive.ts:

import {Directive, ElementRef, Input} from '@angular/core';

@Directive({ selector: '[confirm]' })
export class ConfirmDirective {
    constructor(el: ElementRef) {
        $(el.nativeElement).on('click', function () {
            $(this).confirm({
                confirm: function () {
                    return true;
                }
            });

            return false;
        });
    }
}

Confirmation box does appear, but the event is fired before it, so it is useless. I want this directive to stop an event from firing, fire it if the action is confirmed, cancel it otherwise.


Solution

  • You can actually combine directive name and output together.

     <button class="btn" (confirm)="delete()">delete</button>
    
     @Directive({
       selector: '[confirm]'
     }) 
     export class ConfirmDirective {
       @Output() confirm = new EventEmitter<any>();
    
       constructor(private el: ElementRef) {
       }
    
       @HostListener('click')
        onClick() {
          $.confirm({
          buttons: {
         confirm: () => this.confirm.emit()
       }
      });
     }
    }