Inter-component communication within nested structures in Angular 2

Working on an Angular2 project that involves multiple nested components, I have successfully sent data from a child component to its immediate parent. However, when dealing with three levels of nesting, the question arises: How can I send or modify data across multiple parent components?

For instance, in the scenario depicted above, No 1 represents the message-center component. No 2 is the message-list component which is invoked within No 1 component's HTML using the selector < message-list [messageList]="mails" >.

No 3 portrays a message-detail component, with its parent being No 2. Now, if we delete a selected message from the Inbox within the No 3 component, that message should also be removed from the message-list component (No 2). Furthermore, in the No 1 component, the label "Deleted" should update to "Deleted(1)" as well. How can we propagate this change event to multiple parent components in a two-level nested child component such as No 3?

https://i.sstatic.net/TzcZR.png

Answer №1

If you're looking to incorporate a BehaviorSubject in a service, consider implementing it within a Message service. Don't forget to include the do rxjs operator when needed:

 @Injectable()
 export class MessageService {
     public $messages: BehaviorSubject<Message[]> = new BehaviorSubject<Message[]>([]);
     public getMessages() {
        const url = 'your url';
        return this.http.get(url).do(messages => this.$messages.next(messages));
     }
 }

To access your data in a component, inject the service and utilize the method as shown below:

 msgService.$messages.subscribe(messages => this.messages = messages); // update data each time next is called
 msgService.getMessages().subscribe(); // perform the http call

When deleting a message, simply update the list by using next:

const newList = this.messages.filter(message => message.id !== deletedMessage.id);
msgService.$messages.next(newList);

This will automatically update the data for you. Hopefully, this explanation proves helpful.

Answer №2

By utilizing EventEmitter in component 3, I successfully carried out the notification task. To trigger an action in component 1 based on an event in component 3, I informed component 2 - the direct parent of component 3, which then passed on the notification to its parent component 1. Though it may seem a bit complicated, this approach actually simplifies the process.

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

Utilize Javascript to trigger AJAX refreshes only when necessary

I have developed a web application that displays data fetched from an AJAX request to a PHP script on the same server. This particular application involves playing music from Spotify, and in order to ensure the displayed information is always up-to-date ...

Bold Chutzpah: Delving into AngularJS Testing using Jasmine and TypeScript

Currently, I am utilizing Angular 1.4.9 in combination with Jasmine 2.2.0 and Chutzpah 4.2.0. My Angular code and unit tests are both written in TypeScript within Visual Studio 2015 Update 1. The issue I am facing mirrors that which was previously discuss ...

Navigating a collection of objects in JavaScript: A step-by-step guide

My data consists of objects in an array with the following structure: [{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}]; To clean up the array, I'm using this code: ...

Having performance issues with an HTML5/JavaScript game on Internet Explorer 8

A new game has been developed using html/javascript. Due to confidentiality reasons, the code cannot be fully shared. The game runs smoothly on most browsers except for IE, which poses a challenge. Compatibility with IE8 is essential, despite its limitati ...

Display JSON data in a dynamic d3.js visualization

Using d3.js, I have created a chart that displays weekly scores when hovering over the months. To view the chart, click here: https://jsfiddle.net/qp7L1hob/1/ In my database, I maintain a table called Table pointsScored where I keep records of employee s ...

Accessing PageController through XmlHttpRequest is not allowed in Shopware 6

I'm encountering an issue when attempting to send a request to my customized StorefrontController on the most recent version of Shopware 6.2.2. The error message I'm receiving is: PageController can't be requested via XmlHttpRequest. I&apos ...

Unable to install react-dom/test-utils using npm

I recently included two libraries in my package.json "devDependencies": { ... "react-dom/test-utils": "*", "react-test-renderer/shallow": "*" }, These were recommended by the React documentation to align with version 16 of the React ecosy ...

Conceal the information within a table using angular js and HTML

Just starting out with angular and I have a table that displays angular data directly in the HTML without any controller or model. <table width="98%" border="0" cellspacing="1" cellpadding="2" class="labels" align="center" id="locc"> <tr style ...

Error message: "Property 'item' is not found within type 'P' - The property is inaccessible in the higher order component even though it is included in the props."

I am currently learning about typescript and exploring how to use Higher Order Components (HoCs) with React in a specific scenario. In my case, I am trying to wrap a component with an HoC that checks whether the "item" passed into the "wrapped" component ...

Optimizing normals for unindexed BufferGeometry in Three.js

Currently, I am attempting to refine the normals of a mesh starting from an non indexed BufferGeometry. A similar query has been addressed in the past, however, the Three.js API has undergone significant changes since then and I am unable to make it work o ...

Discover all related matching documents within a string array

I am using a mongoose schema model with a field called tags which is an array of strings to store tags for each document. I need functionality where if I search for a specific tag, such as "test," it will return all documents with tags like "testimonials" ...

Modify the color or background color of a disabled Material UI checkbox

The disabled unchecked checkbox appears too subtle to me, and I would like to enhance it by giving it a grey background and changing the cursor style to not-allowed. I've been trying to implement these styles on the checkbox using the makeStyles, but ...

Switching CSS styles - seeking a smoother integration

I have successfully implemented a JS CSS switcher, which works brilliantly. However, I would like it to function more seamlessly. When opening a new page on the site, the default CSS style sometimes flickers briefly before the selected CSS style is reappli ...

CSS - Absolute positioning appears to be slightly choppy in Microsoft Edge

I have successfully implemented a slip scrolling function to reveal/hide a fixed logo on scroll, but I am facing some issues with Microsoft Edge browser. While testing in various browsers, everything works smoothly except for Microsoft Edge. In this brows ...

What makes FC function components stand out from traditional vanilla React function components?

I recently came across this FC function component: const LabelForm: FC<LabelFormProps> = ({ labels, selectedID, }) => { const selectedLabel = selectedID !== undefined && labels[selectedID]; In my usual implementation, I do it like t ...

Here's a guide on how to package and send values in ReactJs bundles

I'm currently involved in a ReactJs project that does not rely on any API for data management. For bundling the React APP, we are using Webpack in the project. The challenge now is to make the React APP usable on any website by simply including the ...

Tips for assigning the result of a Fetch API call to a variable

Hello everyone! I'm currently working on a project that requires me to retrieve the latitude or longitude of a location using the Google Maps API. However, I am facing an issue with returning values using the Fetch API and its promises. I have succe ...

Is there a way to refine a table based on the specific rows that are chosen in ag-Grid?

Is it possible to filter a table by rows with the attribute select: true, considering that select is not part of the data but rather an attribute of RowNode? I have tried using gridApi.getSelectedNodes() as well as text and number filters, but haven' ...

Issue with Enter key not working on an individual textbox within Javascript/PHP chat functionality

Recently, I created a chat feature with text boxes that send messages when the ENTER key is pressed. However, I encountered an issue with it not working for the "Warning" functionality. Whenever I press Enter in this context, nothing happens. Can anyone pr ...

The content within the mat-card-content paragraph exceeds the boundaries of the mat-card container,

I recently began working with Angular Material and came across an issue. When I have a shorter text paragraph, it overflows the card. However, when I use a larger paragraph, the text wraps nicely. Here is the code snippet: <mat-card *ngFor="let s ...