3

I am creating a reusable component which is showing a rounded image thumbnail as content. I want to detect within this component if a developer has assigned a click listener to it and modify the style and behaviour of it slightly. Basically add a cursor: pointer style if a developer assigned a (click)=anyClickCallbackFunction() on the component.

The question is, how can i read this from within the component?

DArkO
  • 15,880
  • 12
  • 60
  • 88
  • https://stackoverflow.com/questions/28056716/check-if-an-element-has-event-listener-on-it-no-jquery – kcsujeet Jul 12 '19 at 11:27
  • One simple approach would be to pass a boolean prop from the parent to determine whether the child comp has a click event or not: `` – Andrei Gătej Jul 12 '19 at 12:25
  • 1
    Thanks, so it seems it's not possible, yes passing in a boolean is an option, but this is not ideal, as its error prone. – DArkO Jul 12 '19 at 12:32

1 Answers1

4

for doing that you need to have click output in your component although you are not using it, then check how many observers exists

export class MycompComponent implements OnInit {

  @Output() click : EventEmitter<any> = new EventEmitter<any>();

  hasHandler : boolean;

  ngOnInit() {
    this.hasHandler = this.click.observers.length > 0;
  }

}

see working example here

Reza
  • 18,865
  • 13
  • 88
  • 163
  • I am having some more difficulties with this. I am trying to listen for the click event in the component as well by adding a @HostListener('click'). In this case the observers.lenght is always 1, regardless if i add a (click)="onClick()" on the component. Is there a workaround for this? – DArkO Jul 16 '19 at 15:28
  • @DArkO can you fork my stackblitz and modify it to show your issue – Reza Jul 16 '19 at 17:43
  • Here it is demoing the issue: https://stackblitz.com/edit/angular-check-event-handler-exists-r7xzbd – DArkO Jul 17 '19 at 07:29
  • check this workaround https://stackblitz.com/edit/angular-check-event-handler-exists-cm1tk4 – Reza Jul 17 '19 at 12:26
  • @DArkO btw I found out we should check number of subscribers in observers (not the observers), btw that one is always 1 – Reza Jul 17 '19 at 14:33
  • I was thinking the same thing when i found the issue, but i was inspecting the event emitter and i couldn't find any point where the 2 subscriptions are registered. – DArkO Jul 18 '19 at 07:36