Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8: send event from one component to sibling component

I have a sidebar component and a page component.

The sidebar component has a @ViewChild which is an ngbAccordion from Angular Boostrap. I want to trigger its collapseAll method from the page component.

So the sidebar has

  @ViewChild('webAccordion', { static: false })
  webAccordion: NgbAccordion;
  @ViewChild('pageAccordion', { static: false })
  pageAccordion: NgbAccordion;


  collapseAllAccordions() {
    this.webAccordion.collapseAll();
    this.pageAccordion.collapseAll();
  }

When the "page" component loads, I want to emit an event to the "sidebar" component that triggers my collapseAllAccordions function.

I know how to do this with parent/child components, and most of the stuff I can find with Google and here on SO discusses parent/child situations. Except in my case they are sibling components. I'm not sure how to hand siblings.

like image 980
Steve Avatar asked May 24 '26 13:05

Steve


1 Answers

You can use a service:

  • Inject a service into two sibling components.
  • Add an emitter or an Observable to the service.
  • Add a function in the service to change the value of the Observable / emit a new value if your using an emitter.
  • Use the function in your "page" component.
  • Subscribe to the emitter or the Observable in your "sidebar" component and trigger collapseAllAccordions.
like image 170
Ethan Vu Avatar answered May 27 '26 02:05

Ethan Vu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!