Updating the parent component upon navigating from the child component in Angular app

Struggling with updating the parent component after routing from a child component. Through research, I've learned that ngOnInit only runs once. Any way to work around this issue? I've experimented with different lifecycle hooks, but no luck so far. Could really use some assistance! THANKS!

Here are my routes:

{
    path: 'dashboard',
    component: DashboardComponent,
    children: [
        {
            // No child component visible on dashboard
            path: '', 
        },

        {   // Detail component
            path: ':table/:id', // 
            component: DetailComponent,
        },
        // Additional child routes and components...
    ]
}

ngOnInit within Dashboard Component (parent)

ngOnInit() {
    this.getSomething1(); // Populates an array
    this.getSomething2(); // Populates another array
}

When a user selects an item from either array above, they're directed to the detail page for editing/deletion.

Function in child component - when an item is deleted, user is routed back to the parent component:

deleteItem(item: any) {
    // Code to delete item
    this._router.navigate(['dashboard']); 
}

All works as expected except for the fact that the array of items isn't updated because ngOnInit only runs once. I'd like to trigger the methods getSomething1() and getSomething2() again when the user returns to DashboardComponent from DetailComponent.

Appreciate any guidance provided!

Answer â„–1

To address this issue, one approach is to utilize Subjects.

Within the DashboardComponent, you can define a Subject like so:

public static updateData: Subject<any> = new Subject();

Then, you can subscribe to it in the constructor:

constructor() {
      DashboardComponent.updateData.subscribe(res => {
         this.fetchList(); // retrieve data into an array
         this.processData();
      });
   }

In the DetailComponent, after deleting an item, trigger the subject by calling next:

deleteItem(item: any) {
    // some code... 
    DashboardComponent.updateData.next(false);
    this._router.navigate(['dashboard']); 
}

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

Tips for incorporating live stock price updates into an Ionic application

Using a 3rd party API, I have successfully displayed a list of stock prices on cards. However, I am struggling to update the real-time data on each card with each second changes. I have attempted various methods, but the entire API is being fetched inste ...

Angular - Jest can manage the importing of the main entry point

Currently, I am attempting to create a simple test for a component that utilizes rete.js. However, the test is failing due to difficulty handling one of the required import paths. Component import { Component, ElementRef, Injector, ViewChild } from ' ...

Converting Data Types in Typescript

So I'm working with Data retrieved from a C# Rest Server. One of the values in the array is of type Date. When I try to perform calculations on it, like this: let difference = date1.getTime() - date2.getTime(); I encounter the following error messag ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...

How to set the default theme color for the mat-sidenav background in Angular 6 and 7?

Is there a way to make the background of a mat-sidenav match the theme color of my mat-toolbar? In the file src\styles.scss, I have the following: @import '~@angular/material/prebuilt-themes/indigo-pink.css'; The template / HTML file incl ...

Ways to extract X-Total-Count from json-server using Angular's http.get function

Currently, I am utilizing json-server on localhost:3000. The setup is running smoothly, and I can fetch data in Angular through http.get. My objective is to access the response header X-Total-Count within the Angular .subscribe method. However, I am unab ...

Angular 13 vulnerability alert triggered by loader-utils bug

After updating to Angular version 13, I discovered 5 critical vulnerabilities: loader-utils <=1.4.1 || 2.0.0 - 2.0.3 Severity: critical Prototype pollution in webpack loader-utils - https://github.com/advisories/GHSA-76p3-8jx3-jpfq Prototype pollution ...

Unable to access property 'create' which is undefined

On my Ionic3 page, I am trying to trigger a modal open from within a click event function. export class HomePage { .... .... .... loadPos() { var randomLocations = Microsoft.Maps.TestDataGenerator.getLocations(5, this.map.getBounds()); ...

How can we dynamically render a component in React using an object?

Hey everyone, I'm facing an issue. I would like to render a list that includes a title and an icon, and I want to do it dynamically using the map method. Here is the object from the backend API (there are more than 2 :D) // icons are Material UI Ic ...

Enforcing type safety for mysql2 results in Typescript leads to robust data handling

I have been working on a project using NextJS and Typescript where I need to properly type my MySQL responses. This is the API endpoint I am working with: import { hash } from "bcrypt"; import type { NextApiRequest, NextApiResponse } from "n ...

Accessing the Parent Variable from a Function in JavaScript: A Guide

How can you properly retrieve the value of x? let x = 5 const f = (n:number) => { let x = "Welcome"; return x * n // Referring to the first x, not the second one } Also, what is the accurate technical term for this action? ...

Error: The function webpackMerge.strategy does not exist

I've been in the process of updating an older Angular project to the latest version of Angular. However, I'm encountering a problem when trying to build, and I'm unsure why this is happening. Below is the error message that I've receiv ...

Exploring the methods for monitoring multiple UDP ports on a single address in Node.js within a single process

I am currently working on developing a Node.js application to manage a small drone. The SDK provides the following instructions: To establish a connection between the Tello and a PC, Mac, or mobile device, use Wi-Fi. Sending Commands & Receiving Responses ...

Attempting to bind an input parameter using NgStyle in Angular version 2 and above

Issue: I am in need of a single component (spacer) with a width of 100% and a customizable height that can be specified wherever it is used in the HTML (specifically in home.html for testing): number 1 <spacer height="'200px'"></spa ...

Ways to change a value into int8, int16, int32, uint8, uint16, or uint32

In TypeScript, the number variable is floating point by default. However, there are situations where it's necessary to restrict the variable to a specific size or type similar to other programming languages. For instance, types like int8, int16, int32 ...

The object may be null even after being enclosed in an if statement

In my Vue component, I have implemented the following method: dataURLtoBlob(dataurl: string): Blob { const arr: string[] = dataurl.split(","); if (arr) { if (arr[0]) { const mime = arr[0].match(/:(.*?);/)[1]; ...

Invoke a static method from within a class in Typescript (Angular HttpInterceptor)

Recently, I've been working on an http interceptor that was functioning smoothly until just yesterday. It consists of static methods, and for some reason, one of them is now causing issues. Here is the error message displayed in the console: my.c ...

Error during Ng 16 upgrade - npm ERR! Peer dependency conflict found: @angular/[email protected]

I am currently in the process of upgrading my Angular version from 11 to 16. While this Angular documentation has been quite helpful, I am encountering various errors and challenges. Let me provide you with the versions I am working with: Angular CLI: 11. ...

Having trouble with RouterExtension.back() in Nativescript Angular?

I've created a module called TransactionModule that consists of the following routes: transaction-routing.module.ts export const routes: Route[] = [ { path: 'transaction', component: TransactionComponent, canActivate: [AuthGu ...

Creating a blueprint for an object that inherits from another interface

I am looking to create an interface that includes unknown properties for one object, while also extending it with known properties from another interface. Here is my attempt: public async dispatchMessage(): Promise<{} extends IHasResponseFormat> I ...