Update the Angular component once new data is saved in a separate Angular component

I've been diving into the world of MEAN stack and Angular, tackling a method within an angular component called itemListDetailsComponent (found in the .ts file) that looks something like this:

onStatusUpdateClick() {

    this.activatedRoute.queryParams.subscribe((params: any) => {
        console.log('queryParams', params['itemId']);
        this.itemsUpdateService.updateItemStatus(
          params['itemId'],
          this.activatedRoute.data).subscribe(data => {
            this.itemsUpdateService.statusChanged.emit("Status Changed");
        }, error => {super.handleError(error, (err) => {console.log(err)})});            
    });

}

In addition to that, there's another angular component named itemsSideListComponent which presents a list of all items along with their respective statuses. Now, after the itemsListDetailComponent successfully saves and updates the status of the chosen item, I find myself in need of refreshing the displayed list of items within the itemsSideListComponent.

If anyone has insights on how I can achieve this refresh for the list of visible items in the itemsSideListComponent, triggered by the saved/updated data from the selected item in the itemListDetailsComponent, I would greatly appreciate it.

Your assistance is highly valued as I navigate my way through the complexities of angular development.

Answer №1

Ensure your itemListDetailsComponent includes an output event that triggers when an item is saved or updated.

export class itemListDetailsComponent implements OnInit {

  @Output() onSaveOrUpdate = new EventEmitter<Item>();

  onSave(item: any) {
    // Save and emit the event.
    this.onSaveOrUpdate.emit(item);
  }

  onUpdate(item: any) {
    // Update and emit the event.
    this.onSaveOrUpdate.emit(item);
  }
}

My suggestion assumes that the parent component (where both itemListDetailsComponent and itemsSideListComponent are located) manages the data, while these two components focus on displaying it.

ParentComponent.html

<item-list-detail (onSaveOrUpdate)="doRefreshList($event)"></item-list-detail>
<item-side-list [listToDisplay]="list"></item-side-list>

This setup requires that itemsSideListComponent accepts the data to display as an Input. So:

export class itemListDetailsComponent {

    @Input()
    listToDisplay: any[];

}

ParentComponent.ts

list: Item[]

doRefreshList(item: any) {

// Perform a server call or add the item to the list...
this.list.push(item);
}

You may need to trigger change detection based on whether your list is mutable or not.

Answer №2

Utilize the event emitter service for your Angular projects.

For detailed instructions, refer to the official documentation here

After completing tasks in one component, emit an event with a specific identifier. Subscribe to this event in another component where you can also pass along relevant data.

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

"Trying to create a new project with 'ng new xxx' command resulted in error code -4048

Whenever I execute 'ng new projectName' in vs code, I encounter the following issue. ng new VirtualScroll ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? SCSS [ http://sass-lang.com ] CREATE Vir ...

What is the best way to delay Angular for 5 seconds before initiating a page transition?

Just a quick inquiry - is there a way to have Angular wait for 5 seconds before redirecting to a different page? I attempted to implement this functionality within my function, but it doesn't appear to be functioning as expected: setTimeout(() => ...

Finding the location of a file within a published web component

I am currently working on a webcomponent where I need to include a link tag in the head section and set the href attribute to a folder within a node module. At this stage, during the development of my component, my project structure looks like this: http ...

What specific category does the enum object fall under?

How can I create a wrapper class for a collection of elements in an enumeration? export class Flags<ENUMERATION> { items = new Set<ENUMERATION>(); enu; // what type ? constructor(enu) { // what type ? ...

Implementing unique behaviors based on data types in Typescript

I'm currently working on a React project where I need to showcase different types of articles, which I refer to as "Previews." These articles can be either text-based or contain images/videos. To handle this, I've defined two interfaces (TextPre ...

Iterating through an array and setting variables according to asynchronous code

I have created a function to loop through an array, call a promise, and update a variable based on the result. The code seems to be functioning correctly, but I am wondering if there is a more optimal way to write it. Any suggestions are appreciated. Tha ...

Exploring the incorporation of an inclusive switch statement within a Redux reducer utilizing Typescript. Strategies for managing Redux's internal @@redux actions

After conducting extensive research, I have yet to discover a definitive answer to this query. There is a question posted on Stack Overflow that provides guidance on how to implement a thorough switch statement: How can I ensure my switch block covers al ...

The scope of the inferred type parameter in the generic TypeScript function is overly broad

I'm currently working on creating a function that takes in another function (a React component) as an argument and then returns a related function. My goal is to define specific requirements for the input function, ensuring that it accepts certain pr ...

Create a sleek and innovative tree user interface in a single line with the power of Angular and fxF

I created a tree with parent and child nodes, but I'm facing an issue where the positions of the checkboxes are not aligned in a straight line. Here is my code snippet: <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle> ...

What is the best way to import a typescript file using a provided string?

I have a directory filled with JSON schemas, all coded in TypeScript. My goal is to import them collectively while preserving the typing, instead of having to write out numerous import statements. These schemas are utilized for validating JSON data being ...

Angular 8 dropdown menu that closes when clicking outside of it

Hello, I am currently using the click function on the p tag. When a user opens the dropdown menu, I want to close it when they click outside of it in Angular. Here is the HTML code: <div class="select_cat"> <p class="cat_name" (click)="openC ...

The optimal location to declare a constructor in Typescript

When it comes to adding properties in an Angular component, the placement of these properties in relation to the constructor function can be a topic of discussion. Is it best to declare them before or after the constructor? Which method is better - Method ...

What's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3 Consider the following JSON data: const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } To update the title using spread synta ...

error: encountering issue with Vue TypeScript Jest tests - '$store' property is undefined

I've been facing issues with my tests failing after a recent npm install. I've tried adjusting versions up and down, but haven't had any success. Interestingly, the $store isn't directly used in any of the components or tests. Despit ...

NestJS's "Exclude" decorator in class-transformer does not exclude the property as expected

I attempted to exclude a specific property within an entity in NestJS, but it appears that the exclusion is not working as expected. When I make a request, the property is still being included. Code: // src/tasks/task.entity.ts import { Exclude } from &ap ...

Prevent selection of future dates and display them in a muted grey color in the p-calendar component

I am attempting to prevent users from selecting future dates and visually distinguish them by setting a grey color background. However, I am having trouble disabling the future dates while the grey color background is functioning correctly. Any ideas on ho ...

The type 'RefObject<HTMLDivElement>' cannot be matched with type 'RefObject<HTMLInputElement>' in this context

Encountered an error message: Issue with assigning types: Type '{ placeholder: string | undefined; autoComplete: string | undefined; "data-testid": string | undefined; onChange?: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement&g ...

Error: `__WEBPACK_IMPORTED_MODULE_1_signature_pad__` does not function as a constructor

I recently discovered the angular2-signature-pad library for capturing signatures in my Angular project. I attempted to integrate the library using the following steps: // in .module.ts file import {SignaturePadModule} from "angular2-signature-pad"; @NgMo ...

Choose the initial selection from a list of changing values using Ionic

I'm having trouble selecting the first option in an Ionic select. I've written a condition based on indexes where if the index is 0, checked should be true, but it's still not working. Here is my code: <ion-item> <ion-l ...

Leverage JSON files for pagination in NextJS

I am currently developing a science website where the post URLs are stored in a static JSON file. ScienceTopics.json- [ { "Subject": "Mathematics", "chapters": "mathematics", "contentList": [ ...