Exploring Angular 12: How to Handle Events from Multiple Children in a Parent Component

I am new to Angular, especially when it comes to handling events.

Recently, I have been developing a project where the parent Component named Layout consists of multiple child components responsible for performing CRUD operations using different services.

The Layout component includes a navigation bar that displays the number of items in my inventory for each category.

Goal : Whenever an Add or Delete operation is performed in any of the child components, the parent component should trigger a request to the backend to update the item count from the database.

Issue : I am unsure about the correct approach for this. I understand that I need to listen to events from each child component, but I am not sure how to do it.

Should I be listening to the components directly or subscribing to each service and waiting for events to be emitted?

What would be the most efficient way to achieve this?

Due to the length of my code, I will provide relevant fragments to clarify my implementation:

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 №1

Implementing a Shared Data Service

If you want to share data across different components in your application, consider implementing a shared data service. This approach allows you to easily access and manipulate shared data from various parts of your application.

Utilizing the onActivate Method

In the child.component.ts file:


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

deleteItem(id) {
    this.deleteEvent.emit(id);
}

addItem(data) {
    this.addEvent.emit(data);
}

In the parent component template:

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

In the parent.component.ts file:


onActivate(componentRef) {
   componentRef.deleteEvent.subscribe((id) => {
      // Handle deletion event
   });
   
   componentRef.addEvent.subscribe((data) => {
      // Handle addition event
   });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mentioning a specific key more than once within a data structure

Sorry for the vague title, I'm struggling to articulate this idea. Here is a type definition that I have: type Foo = { a: number, b: string, c: boolean, } I am looking to utilize this type as follows: type FooInfo = { property: keyof Foo, ...

Cannot get the arrow to rotate using Jquery's css() function

Having trouble using css() to rotate my arrow $(function() { $("#arrowAnim").css("transform:","rotate(300deg)"); }); Check out the fiddle here: https://jsfiddle.net/u4wx093a/10/ I've looked for similar issues but can't seem to solve it on my o ...

What is the best way to generate an HTML table using Angular from a multi-dimensional array dynamically?

I'm encountering an issue while attempting to dynamically generate an HTML table from JSON data that includes a sub array. The problem arises when trying to create the <td> elements for the sub array. An example of what I am trying to achieve is ...

Universal variable arguments

Is there a way to modify this function that accepts generic rest parameters to also accept an array parameter without using the spread operator? This would make chaining things much clearer: function fn<T>(...args: T[]): Something<T> { } let s ...

The React engine is triggering an error stating "Module not found."

Utilizing react-engine to enable the server with react component access. Through react-engine, you can provide an express react by directing a URL and utilizing res.render. The documentation specifies that you need to supply a path through req.url. app.use ...

The $q.all() function in angular seems to struggle with resolving properly

Having trouble with 3 $http calls in a factory. Creating 4 promises: var promise = $q.defer(), PBdeferred = $q.defer(), Rdeferred = $q.defer(), Pdeferred = $q.defer(); Making the first call to the API: $http.get('/pendingBills').then(fu ...

Use jquery and json to automatically populate select fields based on specific threshold values when they are changed

Looking for guidance on using jQuery to dynamically populate four select fields based on a four-level JSON array for a webshop, depending on threshold values. I'm seeking help with dynamically changing the selects only if the given value is greater t ...

Can the Vue instance be accessed in Axios interceptors?

I've integrated vue-reactive-storage to have a reactive alternative to localStorage in my Vue application. This plugin creates a vue object that is accessible to all components. I'm facing an issue when trying to access this object within my axio ...

The field 'user' is not recognized on the object type WritableDraft

I've set up a redux userSlice to retrieve user data from the store. client/src/redux/features/userSlice.ts import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit"; import { User } from "../../interfaces/user&quo ...

Tips for Checkbox Group validation in Angular JS and Angular Material upon clicking

I have encountered an issue while using Angular Material for simple validation with checkboxes. The Challenge : Requirement: At least one checkbox must be checked. 1- When I click a checkbox and then click again, the "required message" does not appear. ...

The premature firing of the fireContentLoadedEvent in Internet Explorer is causing issues

I've encountered a strange issue with IE8 recently. My code has been functioning properly for a while and still works perfectly in Firefox, but all of a sudden Prototype has stopped calling my event listeners for dom:loaded. I typically attach them u ...

My images are receiving a hidden style display none from Bootstrap js

My images are not loading properly when using Bootstrap v5 on my website. I have no issues with images in other parts of the site. This is the HTML code I am using for the image: <img border="0" src="example.com/img/kitties-long.png" ...

Is Jquery getting imported correctly, but AJAX is failing to work?

I am currently working on a Chrome extension that automatically logs in to the wifi network. I have implemented AJAX for the post request, but when I inspect the network activity of the popup, I do not see any POST requests being sent. Instead, it only sho ...

I wonder which javascript framework Facebook is utilizing

Can anyone share insights on the specific JavaScript framework that Facebook is currently utilizing? Appreciate any input, thank you! ...

If I include the '=' symbol with the request value, the request params will be null

I am currently working on a node.js project that utilizes the express framework. The main purpose of my application is to handle multiple POST requests. One of these POST requests is as follows: URL POST /processit request params info={"one":"a=5"} n ...

Limit certain website functions exclusively for members

I am currently working on a website that offers a set of basic features for all users, along with some exclusive features reserved for members. For example, all visitors can read posts, but only members have the ability to add tags, share posts, and more. ...

Display the duplicated values of an array extracted from a JSON object just once

Having some trouble creating a list from json data, you can check out the example. My goal is to display each value only once if duplicates occur (for example, if there are 2 Martini glasses, I only want one to appear in the list), while still preserving t ...

What steps should I take to address the ES6 promise chain issue within Express?

Currently, I am delving into Promise chaining and experimenting with some code involving express and mongoose in a node environment. Below is the snippet of code that I am working on: const register = (req, res, next) => { User.findOne(req.params.ema ...

What are the best practices for managing security on your AWS Amplify web application?

When working with AWS Amplify & DynamoDB in an Angular web app, how can I secure my Amplify resources to prevent unauthorized access from external sources? An important concern lies in exposing the Amplify configuration within the Angular code, making it ...

Exploring the shapes and dimensions of a truncated Icosahedron in preparation for graphic design purposes

I am attempting to create a truncated icosahedron design with interactive clickable areas using Three.js. Initially, I came across code for a standard icosahedron: var t = ( 1 + Math.sqrt( 5 ) ) / 2; var vertices = [ [ -1, t, 0 ], [ 1, t, 0 ], [ ...