简体   繁体   English

带有Angular2中同一元素上的Click侦听器和click事件的指令

[英]Directive with click listener and click event on the same element in Angular2

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

What happens when an element has a directive (appMenuDropDown) listening for a click event and a click event handler (getSubMenuItems()) ? 元素具有指令(appMenuDropDown)来监听click事件和click事件处理程序(getSubMenuItems())时会发生什么? Which handler gets triggered first ? 哪个处理程序首先被触发? Handler in directive or getSubMenuItems() ? 指令或getSubMenuItems()中的处理程序?

@HostListener('click')
clickListener() {
    let sourceElement = this.el.nativeElement;
    ....
}

The order of event handlers is explicitly undefined. 事件处理程序的顺序是明确未定义的。 Also if you have several directives on an element, the order they are added is not significant to the order event handlers are processed. 同样,如果在一个元素上有多个指令,则它们的添加顺序对于处理顺序事件处理程序并不重要。

I think that in your case HostListener within directive will be always fired first 我认为在您的情况下,指令中的HostListener总是会先被触发

You can take a look at generateHandleEventMethod method within compiler from source code 您可以从源代码中查看编译器中的generateHandleEventMethod方法

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

https://github.com/angular/angular/blob/2.2.4/modules/%40angular/compiler/src/view_compiler/event_binder.ts#L92-L115 https://github.com/angular/angular/blob/2.2.4/modules/%40angular/compiler/src/view_compiler/event_binder.ts#L92-L115

and here is generated component.ngfactory 这是生成的component.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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM