1
votes

I have a sidebar in my app.component. I want to be able to update it from multiple child components. There is a sample here on how to send data from child to parent component:

https://dzone.com/articles/understanding-output-and-eventemitter-in-angular

However the sample binds the parent to a specific child component:

import { Component, OnInit } from '@angular/core';
@Component({
    selector: 'app-root',
    template: `<app-child></app-child>`
})
export class AppComponent implements OnInit {
    ngOnInit() {
    }
}

As you can see the template a bound to app-child specific. How can you make a more generic solution so multiple children can send an event to update menus?

2

2 Answers

2
votes

Communication via a service keeps it wholly generic. This is not limited to parent child comms but comms between any 2 components:

Docs are here - https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

Basically, the component that wants to send data sends the data to a service method. The service then emits (next(data)) to a subject. Anything subscribed to the subject then receives the data.

You can provide the service at root level these days using:

@Injectable({
  providedIn: 'root'
})

Without having to list it in your providers array. I think this is Angular 6 only. Then the service is loaded on demand. Alternatively, you can provide the service in a providers array.

If you want to get more technical check out ngrx which provides a global store solution.

2
votes

One approach I can think of is have something like a sidebar service that your sidebar component injects.

Inside the sidebar service you could have a BehaviourSubject which your child components could also access and emit values on that you could listen for in your sidebar component and react accordingly.

Edit - just as I posted that, another answer came in which confirms my line of thought!