What is the best way to refresh or reload a child component in Angular?

I have a transaction.component.html file that displays the app-deal-partners component. Every time the delete function is triggered, I want to refresh and reload the child component, which is the app-deal-partners component.

I need to reload

<app-deal-partners [transaction]="transaction" [forApprovalResponse]="forApprovalResponse"></app-deal-partners>

How can we achieve this in Angular? Thank you.

#transaction component ts code

 delete(rowData: any) {
    this.isLoading = true;
    this.Service.delete(rowData.id)
      .pipe(finalize(() => { this.isLoading = false;}))
      .subscribe({
        next: (res) => {
        },
        error: (err) => {
          this.notificationService.showError('Something went wrong, Try again later.');
          this.isLoading = false;
        },
        complete: () => {
          this.isLoading = false;
        },
      });
  }

#transaction.component.html code rendering app-deal-partners code

  <div style="padding-bottom: 20px;">
    <app-deal-partners [transaction]="transaction" [forApprovalResponse]="forApprovalResponse"></app-deal-partners>
  </div>

#app-deal-partners HTML code

 <app-table-multi-sort (dataServiceEvent)="dataServiceEvent($event)" [tableOptions]="tableOptions" [tableData]="data" (tableActionsEvent)="tableActions($event);" (editRowEvent)="editDeal($event)"></app-table-multi-sort>

Answer №1

To achieve this functionality, you can utilize observables:

private userRemoved: Subject<any> = new Subject<any>();
public userRemoved$ = this.userRemoved.asObservable();
remove(rowData: any) {
  this.loading = true;
  this.Service.remove(rowData.id)
    .pipe( tap(_ => this.userRemoved.next(rowData)), finalize(() => { this.loading = false;}))
    .subscribe({
      next: (res) => {
      },
      error: (err) => {
        this.notificationService.showError('An error occurred, please try again later.');
        this.loading = false;
      },
      complete: () => {
        this.loading = false;
      },
    });
}

Template:

<app-deal-partners [userRemoved$]="userRemoved$" [transaction]="transaction" [forApprovalResponse]="forApprovalResponse"></app-deal-partners>

and the child component logic:

@Input()
public userRemoved$: Observable<any>;

OnInit(){
  this.userRemoved$.subscribe(_ => {
    // Implement your logic here
  })
}

Answer №2

If I had to choose, this is how I would implement it:

<app-deal-partners 
  *ngIf="!isLoading"
  [transaction]="transaction"
  [forApprovalResponse]="forApprovalResponse"
></app-deal-partners>

When the value of isLoading is true, the component gets destroyed, but when it's false, the component is reloaded.

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

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...

Creating an HTML5 video tag with bearer authentication using a WebAPI: The ultimate guide

My ASP.NET WebAPI requires bearer authentication, and most of my requests towards the API follow this format: GET http://localhost:29080/api/v1/users/me HTTP/1.1 Host: localhost:29080 Connection: keep-alive Accept: application/json, text/plain, */* Origin ...

Exploring diverse paging methods tailored to specific devices within Angular 12

Hey there! I'm looking to implement two different paginations for a single table with 20 rows. Here's what I need: For desktop, the first pagination should display 10 rows on the first page and the remaining 10 rows on the second page. As f ...

How can we effectively display the cookie value within the template by utilizing observables and selectors in conjunction with the ngx-cookie-service library?

I'm wondering if there's a seamless approach to leverage observables for dynamically retrieving a cookie value, essentially creating a "reactive" cookie. Although typical solutions involve utilizing this.cookieService.get("cookieName") within ser ...

When utilizing the ngFor directive with the keyvalue pipe, an error occurs stating that the type 'unknown' cannot be assigned to the type 'NgIterable<any>'

I'm attempting to loop through this object { "2021-11-22": [ { "id": 1, "standard_id": 2, "user_id": 4, "subject_id": 1, "exam_date": "2021-11-22" ...

Tips on optimizing NextJS for proper integration with fetch requests and headers functionality

I'm currently working on a NextJS project and following the official tutorials. The tutorials demonstrate how to retrieve data from an API using an API-Key for authorization. However, I've run into a TypeScript compilation error: TS2769: No ove ...

Is it possible to retrieve the form value in Angular that is different from what is displayed?

Is there a way in Angular to retrieve form values differently than how they are displayed? For example, let's say you have an Angular FormInput that displays the value "3,567.56 $" to the user. <input formInputControl="price" money> I want th ...

What is the process for searching my database and retrieving all user records?

I've been working on testing an API that is supposed to return all user documents from my Mongo DB. However, I keep running into the issue of receiving an empty result every time I test it. I've been struggling to pinpoint where exactly in my cod ...

Using TypeScript to Return a Derived Class as a Method's Return Type

I'm currently facing a challenge with an abstract class in typescript that includes a method to provide a callback for later use. The issue lies in the return type of the method, as it is set to the class itself, preventing me from using fluent style ...

Exploring JSONPath in Cypress

I am currently working on extracting a JSON path for the specific HTML content with the language code DE Below is an example of the JSON data: { "name": "Name", "text": "", "html": "HTML content" ...

Using TypeScript to execute a function that generates middleware for an Express application

I've developed a middleware for validating incoming data, but I encountered an issue where a function that takes a Joi object as a parameter and returns the middleware is causing errors during build. Interestingly, everything works perfectly fine duri ...

Can NgZone be utilized within a shared service instance?

I am currently working on creating an injectable singleton service for my application that will provide all components with information about the window width and height, as well as notify them when the page is scrolled or resized. Below is the code snipp ...

What are the advantages of utilizing the HttpParams object for integrating query parameters into angular requests?

After exploring different ways to include query parameters in HTTP requests using Angular, I found two methods but struggled to determine which one would be the most suitable for my application. Option 1 involves appending the query parameters directly to ...

Type of result from a function that returns a linked promise

In my class, I have a method that returns a chained promise. The first promise's type is angular.IPromise<Foo>, and the second promise resolves with type angular.IPromise<Bar>. I am perplexed as to why the return type of doSomething is an ...

Compile time error due to TypeScript enumeration equality issue

Currently, I am developing a system to manage user roles within my website using TypeScript enumeration. This will allow me to restrict access to certain parts of the site based on the user's role. The primary challenge I am facing is comparing the u ...

Implementing multiple modules within a shared parent route in Angular

Currently, I am seeking a method to load multiple modules under the same path in Angular. Let's say I have three modules: AModule, BModule, and CModule, each with its own RouterModule.forChild call. My goal is to combine these modules under the route ...

Adding a backslash in Angular: Tips and Tricks

I have a question about adding a backslash to a string that is returned from a div, for example Car1 \sold. Although I am able to retrieve the status, I am having trouble adding the backslash. Here is what I have tried so far: <span>{{addBackl ...

TS2304: The build process is unable to locate the name 'iterable' within @types

As an experienced dog attempting to master new tricks like npm and TypeScript, I find myself faced with a challenge in my Visual Studio 2017 project. Despite setting it to "Latest" TypeScript 2.5 and adding @types/jquery (3.2.12), the project keeps throwin ...

What is the rationale behind an Angular component needing to duplicate an object provided by a service?

As I dive into the HttpClient page within the Angular Fundamentals section, one question that comes to mind is why does the component need to clone the object received from the service handling the HTTP calls? In particular, the code block from the config ...

Designing a versatile Angular component for inputting data (Mailing Address)

Currently, I am in the process of developing an Angular 11 application that requires input for three distinct mailing addresses. Initially, I thought I had a clear understanding of what needed to be done, only to encounter warnings about elements with non- ...