简体   繁体   中英

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()) ? Which handler gets triggered first ? Handler in directive or 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

You can take a look at generateHandleEventMethod method within compiler from source code

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

and here is generated 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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