3

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.

Steve
  • 14,401
  • 35
  • 125
  • 230

2 Answers2

2

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.
Ethan Vu
  • 2,911
  • 9
  • 25
0

You could use intermediate singleton service between these components and share the data/actions. For example,

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss']
})
export class SideBarComponent implements OnInit {
  constructor(private service: AppService) { }

  onClick() {
    this.service.collapse();
  }

  ngOnInit(): void { }
}


import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-page',
  templateUrl: './page.component.html',
  styleUrls: ['./page.component.scss']
})
export class PageComponent implements OnInit {
  constructor(private service: AppService) { 
    // Create a observable object which listens to service and 
    // change the behaviour of current page component and vice versa
  }

  ngOnInit(): void { }
}

If you require further assistance please create stackblitz or codesandbox to replicate this issue.

Daniel Inbaraj
  • 778
  • 8
  • 9