angular - 如何将事件绑定(bind)到指令?

标签 angular angular2-directives

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

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

我的默认(onDropSuccess)="onDropSuccess($event)",拾取事件,我可以做所有事情,但如何通过指令传递它,因为我想( 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

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

关于angular - 如何将事件绑定(bind)到指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685253/

相关文章:

angular - Angular 2 中的延迟加载文件夹

angular - Angular2Dart Router.currentInstruction未设置

angular - 获取对象可能是 'null' 。在 Angular 模板文件中

javascript - 如何获取 Angular 2中的第一个父scrollTop元素?

typescript - 以 Angular 2 扩展 routerLink?

rest - 使用一个 REST 调用的 Angular2 多个组件

angular - 使用 EventEmitter 传递参数

angular - 为什么 Angular 2 中的 ngx-leaflet 在通过 *ngif 更改状态后不渲染 map

angular - 由于错误 : Error: Module build failed: Error: ENOENT: no such file or directory, 打开,预呈现失败

javascript - 使用 NGRX 更改状态后如何执行一些代码?