5

I've created a simple component with template:

<div (click)="onClick();">Click me</div>

In *.ts file I've got something like that:

public onClick() {
    console.log('click');
}

@HostListener('document:click', ['$event'])
public onClickListener(event: Event) {
    console.log('click listener');
}

In this case onClick function is called always before onClickListener.

My goal is to invoke some method before Angular (click) or (routerLink) etc.

It's possible?

What is important - this listener should be a global method, which handle all clicks during runtime.

5
  • What are you trying to invoke before click. Why can it not be handled in the click event? Commented Dec 20, 2017 at 18:34
  • I'm sure I understand properly your issue. Why not just do : public onClick() { methodToExecuteBefore(); console.log('click'); } ? Commented Dec 20, 2017 at 18:34
  • Because onClickListener will be in root (main) component finally and must handle all clicks (not only (click)). Commented Dec 20, 2017 at 18:39
  • Do you want to handle clicks anywhere in the application, or only on buttons? Commented Dec 20, 2017 at 19:08
  • Anywhere. Each click is important. Commented Dec 20, 2017 at 19:10

1 Answer 1

1

If you want to handle the click events anywhere in the application before they are handled by Angular, you can add a click event listener to the window and specify that the event will be processed in the capture phase. In the following code snippet, addEventListener("click", fn, useCapture) is called with useCapture set to true (see the MDN documentation).

window.addEventListener("click", () => {
  console.log("Global click handler");
}, true);

You can see it at work in this plunker.

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

2 Comments

very nice implementation
And that is what I was looking for.

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.