Home > Net >  How to call component method inside sibling component without creating a service?
How to call component method inside sibling component without creating a service?

Time:08-01

I have an angular project in which I have 3 components: container, sidenav, main-content.

container.component.html

<mat-sidenav-container>
  <app-sidenav></app-sidenav>
  <app-main-content></app-main-content>
</mat-sidenav-container>

sidenav.component.ts

is_open = false;

toggleSidenav() {
  this.is_open = !this.is_open;
}

I need to retrieve the is_open value from the main-content component.

My idea was to create a template reference from app-sidenav (let's say #sidenav) and use its property inside main-content.component.html (sidenav.is_open) but how do I achieve this?

I know I can create a service for that but since it's only for one property (is_open), I don't want to create a single service for this. Or am I seeing this wrong?

CodePudding user response:

To communicate between two Angular components there are multiple strategies such as:

  • @Output() and @Input()
  • Service with Observables
  • Setters and Getters
  • Third party state management libraries (NgRx)
  • Component Injection

Since you are not interested in the services (And I do not see in your question what is the constraint) you can simlply use @Input() and @Output which are available here in the documentation to help you understand how to facilitate the communication between parent and child components in Angular.

  • Related