Search code examples
angularangular2-directives

How do you bind an event to a directive?


I have my directive and I would like to pass to the directive the $event.

I am dropping an element on the div and via the event I pass the obj that I am dropping.

My default (onDropSuccess)="onDropSuccess($event)", picks up the event and I can do everything, but how do I pass it via the directive as I would like to on (onDropSuccess) pass the event to my colordrop directive and do some magic functions there.

Directive

import { Directive, ElementRef, Input, Output, EventEmitter, OnChanges, HostListener, ViewChild, ViewChildren} from "@angular/core";

@Directive({
    selector: '[colorDropModel]',
   host: {
    '(onDropSuccess)' : 'addColor()'
    }
})

export class colorDropDirective  {
@Input() colorDropModel: string; 
  constructor(  private _elementRef: ElementRef){}

  addColor(event) {
    console.log('colorDropModel', event)

  }
}

HTML

<div 
    (onDropSuccess)="onDropSuccess($event)" 
    [colorDropModel]="$event"
>
    Dropable area 
</div>

Solution

  • You dont have to add event on div if you are trying to access event for your directive. In your directive you can do this:

    @HostListener('onDropSuccess') onDropSuccess() {
    
      }
    

    and if you want to do some magic on the element you can always get the element reference like this

     _elementRef.nativeElement
    

    and after getting hold of the element you can implement you magic. Hope this will help!