Angular 12: Listening to multiple children events in Parent component

I’m a beginner to Angular when It comes to events and such.

Lately I’ve been working on this project where I have a parent Component called Layout, which contains multiple child components that are supposed to do CRUD operations through various services.

Now the Layout component has a navbar and this navbar shows the number of items I have in my inventory for each category.

Objective : When I make an Add or Delete request in one of the children, the parent component is supposed to fire a request to the backend. That way it will retrieve the new number of items from the database

Problem : I don’t knwo the correct approach I should be using here, I know that I need to listen to the events from each child component, but I didn’t know how.

Am I supposed to listen to the components or subscribe to each service and wait for it to emit an event ?

What’s the best way to do this ?

My code is quite long so I’ll add some fragments to clarify what I’m doing:

Layout.component.ts

 ngOnInit(): void {
        this.prepareNavbar()
    }

Layout.component.html

<nav> 
<!-- Here I display the numbers of each item retrieved from the database -->
</nav>
<router-outlet></router-outlet>

AddItem1.component.ts

addItem(){
this.Categorie1Service.addItem.subscribe()
}

DeleteItem.component.ts

DeleteItem(){
this.Categorie2Service.DeletItem.subscribe()
}

Answer

Using a Shared Data Service

You can share a dataService over your application, which you have figured out already. Which is a good choice if you want to use the shared data in other places of your application.

Using onActivate

In child.component.ts:

@Output() deleteEvent = new EventEmitter
@Output() addEvent = new EventEmitter

deleteItem(id){
    this.deleteEvent.emit(id)
}
addItem(data) {
    this.deleteEvent.emit(data)
}

In the parent template:

<router-outlet (activate)="onActivate($event)"></router-outlet>

In parent.component.ts:

onActivate(componentReference) {
   componentReference.deleteEvent.subscribe((id) => {
      // implementation
   });
   
   componentReference.addEvent.subscribe((data) => {
      // implementation 
   })
}