Home > Back-end >  Best way to listen for click event across components in Angular 13
Best way to listen for click event across components in Angular 13

Time:05-19

I have a top-nav component which contains a nav menu with a dropdown. When I click the dropdown link, I'd like a background overlay to appear beneath the dropdown menu and covering the page.

I have this hierachy of components. main.component.ts > header.component.ts > top-navigation.component.ts

The click occurs in the top-navigation.component.html and I need to listen for this in the main.component.ts as in the main.component.html I have a span (with corresponding css which is waiting for a class of active to be added on click). <span ></span>

Using @Output with EventEmitter doesn't seem right as I'd need to emit up from top-navigation to header, then emit again from the header up to main (but I could be wrong...).

Should an Observable be used to do this or is that overkill to simply pass an event from one component to another? I have a navigation service but have read an Observable shouldn't be listened for inside a service.

CodePudding user response:

I'm not sure if this is what you are looking for, but as I understand your question, you don't really need to communicate components. If you want, for example, blur the page when hovering (or clicking) in the navbar, what you can do is apllying a background with any dark color, with 100% at width and height, and higher z-index than the page, but lower than the dropdown.

CodePudding user response:

You can use Event emitter to emit that something is click on the nav menu and let child components know about the click. and if you want to pass on data on click you need to pass event emitter as an observable. I hope this is what you wanted as your question is not clear.

  • Related