1
<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;
    ....
}
1
  • I think element's event will be fired first. You can simply console.log both and see... Commented Dec 7, 2016 at 11:20

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

It is indeed directive handler first in all my testing. I was not sure if it is programmed to be in that specific order. Thank you for the demo and the compiled code.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.