如何将事件绑定到指令?

How do you bind an event to a directive?

我有我的指令,我想将 $event 传递给指令。

我正在 div 上放置一个元素,并通过事件传递我正在放置的对象。

我的默认值 (onDropSuccess)="onDropSuccess($event)" 接收事件,我可以做任何事情,但我如何通过指令传递它?到 on (onDropSuccess) 将事件传递到我的 colordrop 指令并在那里执行一些魔术功能。

指令

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>

如果您尝试访问指令的事件,则不必在 div 上添加事件。 在您的指令中,您可以这样做:

@HostListener('onDropSuccess') onDropSuccess() {

  }

如果您想对元素施展魔法,您总是可以像这样获取元素引用

 _elementRef.nativeElement

掌握元素后,您就可以施展魔法了。 希望这会有所帮助!