javascriptangulareventsangular2-directivesangular2-components

Is there a way to emit event inside directive


I use Angular2 and write some @Directive with drag and drop (in some bounded area) and want to emit event when dragging is end - so when dragging is end I invoke method endDragging. 1. how body of this method should look like?, 2. how usage of this directive should look like (especially how to set eventHandler to directive).

@Directive({
    selector: '[draggable]'
})
export class Draggable {
    @Input('draggable') boundary: any;
    ...
    endDraging() {
        // ??? how emit event from here?
    }
}

In html template (???=how set handler for draggable-endDragging event):

<div [draggable]="{x_min:10, x_max:100, y_min:20, y_max:200}" ...???... >
...some content...
</div>

Solution

  • You can define service with global event and use it in directive

    import { Injectable } from '@angular/core';
    import { ReplaySubject } from 'rxjs';
    
    @Injectable({ providedIn: 'root' })
    export class GlobalEventService {
    
        private eventSubject = new ReplaySubject<string>(1);
    
        constructor() { }
    
        public getEventObservable() {
            return this.eventSubject.asObservable();
        }
    
        public emitEvent(message) {
            this.eventSubject.next(message);
        }
    }
    

    Code is out of head and may contain bugs. From outside someone in service do

    globalEventService.getEventObservable().subscribe(message => { … })
    

    while directive use this servis sending event like this

    globalEventService.emitEvent('some messsage')