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

Mastering the art of shaping state in NGRX for the master-detail pattern

Imagine a scenario where I am developing a compact app for organizing tasks. This app makes use of angular and NGRX to efficiently manage the state. Each day, the user loads tasks in the morning and then travels to different locations to complete them. Th ...

How to designate a try / catch block as asynchronous in TypeScript / JavaScript?

I am facing an issue where the code is not entering the catch block in case of an error, try { this.doSomething(); } catch (error) { console.error(error); } This problem occurs when "doSomething" returns a promise or runs asynchronous code. doSome ...

Find all Mondays occurring within a specified date range using Moment.js

I need to extract all Mondays within a specific date range. let start = moment(this.absence.FromDate); let end = moment(this.absence.ToDate); The user has the option to deactivate certain weekdays during this period by setting booleans. monday = true; t ...

Updating Angular model remotely without relying solely on the controller

I am struggling to call the addRectangleMethod method from my Javascript code in order to retrieve server-side information into the Angular datamodel. However, I keep encountering an error stating that the method I'm trying to call is undefined. It&ap ...

Getting a "module not found" error in Next.js while trying to import a TypeScript

Check out this code snippet: // lib/customFunction.ts export function customFunction() { console.log("customFunction"); } // pages/homepage.tsx import { GetServerSideProps } from "next"; // works import { exampleFunction } from "../lib/exampleFile.js" ...

Workspace Settings cannot be saved due to an unregistered configuration

I've been attempting to change the StatusBar color in VScode Setting.json using Configuration and Workspace. However, I encountered an error when trying to make the update: Error: Unable to write to Workspace Settings because workbench.colorCustomizat ...

Google Maps API Version 3 now allows for custom overlays to be hidden when they overlap

I have implemented multiple custom overlays on a map for various cities and I am trying to manage the overlapping ones by hiding or collapsing them. My goal is to display and expand overlays with the highest population whenever there is available space. M ...

HTML various button designs - such as a cogwheel

I need a button on my Angular/Electron project that resembles a gear icon. I came across these resources: here and here. However, when I tried to implement them, they didn't work as expected. Currently, the button looks like this: <button class= ...

Having trouble implementing the Material UI time picker because it does not meet the required DateTime format

REVISE I recently switched my dataType from DateTime to TimeSpan in my code. I have a functioning MVC version that already uses TimeSpan, and the times are posted in HH:MM format. Now, I am unsure if the issue lies with the headers set up on Axios or if it ...

A guide on incorporating a set of components to be utilized as custom HTML elements in Angular

I am in the process of revamping my application to be more modular on the UI side, with a focus on separating different elements including: App header Left navigation panel Main content on the right side of the nav panel I have successfully figured out ...

Resetting and marking an Angular2 form as untouched

Is it possible to reset a form and mark it as untouched, clean, etc after submission while staying on the page to avoid resubmission? this.myForm.reset() this.myForm.markAsPristine() this.myForm.controls['options_name'].markAsUntouch ...

Enrich your TypeScript code by unleashing the power of enum typing in overloading logical

I have a custom enum called PathDirection that represents different directions export enum PathDirection { LEFT="LEFT"; RIGHT="RIGHT"; }; Within my code, I need to toggle between the two directions. For example: let currentDire ...

Using Rails 5 API to generate a new object using JSON with nested resources

Here is the JSON data that was received as parameters from an external Angular web app: { "provincia": { "id": 1, "name": "Province" }, "username": "tester", "direccion": "new avenue 100", "email": "<a href="/cdn-cgi/l/email-protectio ...

Incorporating a picture backdrop into a button element in a React Typescript component

I am working on a React project with TypeScript and using a Material UI library. I am trying to set a background image for a button, but when I use src or imageURL, it gives me a TypeScript error. The CSS style also does not show the picture. Here is my ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Having trouble applying [formControl] to a set of radio buttons in Angular2

Currently, I am encountering an issue with a list of groups of radio buttons in Angular2. My objective is to bind the value of each group of radio buttons using [formControl]. However, when implementing this, the radio buttons seem to lose their normal mut ...

What is the best way to retrieve specific data based on their unique identifier?

Imagine having a table like this, with the following data: Id , Name , IsBillable 1 One 1 2 two 0 3. three 0 I have stored this data in a variable called masterData using the get method, and I am using it to populate a dropdown me ...

What strategies can be implemented to avoid re-rendering in Angular 6 when the window is resized or loses focus?

I am currently working with a component in Angular 6.0.8 that consists of only an iframe element. Here is the code in page.component.html: <iframe [src]="url"> The logic for setting the URL is handled in page.component.ts: ngOnInit() { this.u ...

Struggling with testing the checkbox when it changes inside the CardHeader Avatar={} component

I've recently implemented a feature similar to the example showcased on MaterialUI's TransferList. However, I'm encountering difficulties accessing a checkbox within the avatar={}. The project utilizes Jest and Enzyme for testing purposes. T ...

What is the best way to execute a function on the output of *ngFor directive in Angular 2?

Imagine having a list of all the users within your system: allUsers = { a: {name:'Adam',email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="39585d5854794d5c4a4d5a56175a56... f: {name:'fred' ...