使用单击“侦听器”的指令,然后在Angular2中的同一元素上单击事件


<a appMenuDropDown (click)="getSubMenuItems(menuItem)">
.......
</a>

当元素具有指令(appmenudropdown)侦听点击事件和单击事件处理程序(getSubMenuitems())时会发生什么?哪个处理程序首先触发?指令或getSubMenuitems()?

中的处理程序
@HostListener('click')
clickListener() {
    let sourceElement = this.el.nativeElement;
    ....
}

我认为,在您的情况下,指令中的hostlistener将始终首先被解雇

您可以从源代码中查看编译器中的generateHandleEventMethod方法

directives.forEach((dirAst, dirIdx) => {
  ...
});
boundEvents.forEach((renderEvent, renderEventIdx) => {
  ...
});

https://github.com/angular/angular/blob/2.2.4/modules/@angular/compiler/src/view_compiler/event_binder.ts#l92-l92-l92-l92-l92-l92l115

,这里是生成组件。ngfactory

View_AppComponent0.prototype.handleEvent_4 = function(eventName,$event) {
  var self = this;
  self.debug(4,2,4);
  self.markPathToRootAsCheckOnce();
  var result = true;
  result = (self._AppMenuDropDownDirective_4_3.handleEvent(eventName,$event) && result);
  if ((eventName == 'click')) {
    var pd_sub_0 = (self.context.getSubMenuItems() !== false);
    result = (pd_sub_0 && result);
  }
  return result;
};

demo

事件处理程序的顺序明确未定义。另外,如果您有几个有关元素的指令,则将其添加的订单对订单事件处理程序的处理并不重要。

最新更新