Modify the parent component using dialogRef while keeping the dialog open

Within my application, there is a child dialog connected to a parent component. The parent component contains a MatTable that gets updated when the "update" button in the child dialog is clicked.

The following code in the parent component is functioning perfectly:

parentComponent.ts

 openDialog(e: any) {

    this.data = e;
    const dialogRef = this.dialog.open(DialogAddMarqueComponent, {
      data: this.data,
      restoreFocus: false,
    });

    console.log(this.dialogRef)

    dialogRef.afterClosed().subscribe((result) => {
      if (result.length !== 0) {
        this.products.data.push(result);
        this.products = new MatTableDataSource(this.products.data);
      } else { return; }
    });
  }

I have implemented a new function and button similar to the update functionality but without closing the DialogRef. I aim to replicate the behavior within dialogRef.afterClosed() without actually closing the dialog.

Child Component.ts

this.appService.addProduct(this.product)
    .subscribe(
        response => {
            this.product = response;
            this.products.data.unshift(response);
            // this.dialog.close(response); // that will trigger the dialogRef.afterclosed()

        }, error => {
            console.warn('ERROR', error);
        }
    );

I believe I need to subscribe to the dialogRef on the parent side so that clicking the duplicate button triggers an update in the parent component. However, I am unsure of which dialogRef function to utilize (I attempted Get state). Is there a method to accomplish this?

Answer №1

Dialog cannot detect changes automatically.

To address this issue, I recommend following these steps:

  1. Start by creating a service. (Use command: ng g s <service-name>)
  2. Store your variables in the created service so that you can access them from both pages.

With this setup, any changes made in the dialog will be reflected on the parent page as well.

Answer №2

Once the modal is closed, the afterClosed event will be triggered. In order to achieve a similar functionality, you'll need to explore alternative methods. One approach could involve utilizing a shared service that is injected into both the parent and dialog components to facilitate event triggering.

A potential implementation for the service might resemble the following:

@Injectable({ providedIn: 'root' })
export class MarqueService {
  private updateSource = new Subject<Product>();

  public update$ = this.updateSource.asObservable();

  public updateProduct(product: Product): void {
    this.updateSource.next(product);
  }
}

Subsequently, it is necessary to inject this service into both the parent and dialog components.

export class ParentComponent implements OnInit, OnDestroy {
  private subscription = new Subscription();

  constructor(private marqueService: MarqueService) {}
   
  ngOnInit() {
    const sub = this.marqueService.update$.subscribe((product) => {
      const products = [...this.products.data];
      const index = products.findIndex(prod => prod.id === product.id);
      products[index] = product;
      this.products.data = products;
    });
    this.subscription.add(sub);
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

The dialog component contains the logic to trigger the update upon button click:

export class DialogAddMarqueComponent {
  constructor(private marqueService: MarqueService) {}
  // ...

  handleUpdateClick() {
    // Assuming this.data represents the product being edited
    this.marqueService.updateProduct(this.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

Discovering the process of reaching service members through an HTML View

Currently, I am in the process of learning Angular 2 and find myself unsure about the most efficient way to update the view. For instance, let's say I have two components: User and Main. The User component retrieves a list of users from the UserServ ...

The push action in NavController is not displaying Google Maps as expected

Trying to display a map upon clicking a button is proving challenging for me. It appears that the function NavController.push() does not work as expected, while NavController.setRoot() does. Despite not encountering any errors, I am unable to identify the ...

The API's post call is throwing an error, yet it functions perfectly when tested on

Currently, I have a functional Angular project that connects to real data using WebAPI2. However, I am now working on an Express.js project for demo purposes which mocks the data, providing random information instead of consuming the actual WebAPI2 data. T ...

Can we make one tab disappear when another tab is clicked in Ionic 2 app menu icon?

I am working on a project using Ionic 2 and I have implemented multiple tabs in the application. However, I need to find a way to hide the top tab when the user clicks on the bottom tabs menu icon. Here is my Plunker for your reference. My goal is to ma ...

Compilation error occurs while compiling the Angular Tree component indicating that there is no "Cancelable" exported member

I recently encountered an error while building my Angular application that involved using the Angular Tree Component. After some troubleshooting, I was able to resolve the issue and wanted to share my solution with the community. 2020-09-02T13:10:19.5809 ...

Efficient way to assign multiple values simultaneously in react hook form with Typescript

Here is the interface I am working with: export interface DataResponse { user_id: string; name: string; phone_number: string; country: string; } This interface is used as a type for fetching data using react query. To populate the fields if there ...

Troubleshooting why Angular2 is failing to load external styles in styleUrls

Currently in the process of developing an angular2 application and had envisioned being able to implement distinct styles for public content versus admin content. To my disappointment, it appears that Angular is not accommodating external styles that are l ...

In TypeScript, there is a chance that the object may be undefined, so I make use of an if

I'm encountering an issue with this code snippet. I have a check in place to ensure that the value of 'startups[i].logo' is not undefined, however I am still receiving an error stating that it may be undefined. Can anyone provide insight as ...

Encountering the error "Object potentially undefined" while attempting to activate Cloud Function during document creation

My goal is to automatically create a new authenticated user whenever a new document is added to the "users" collection. The necessary user details will be extracted from the fields "email" and "phone" in the new document. The challenge I am facing is that ...

Choosing a nested for loop structure in TypeScript

Looking for assistance with form group this.orderForm = this._formBuilder.group({ vlanFormGroup: this._formBuilder.group({ vId: ['', [Validators.required, Validators.pattern(this.positiveInteger)]], vName: ['', [Validat ...

Input the variant number TypeScript as the key value pair

I'm struggling to input an abi key "5777" in Typescript. When I receive a network ID and try to set it in the networks key, the linter displays an error. My issue is that I need to specify "networkId" and it's not always a fixed value like "5777 ...

What could be the root of this next.js build issue occurring on the Vercel platform?

I recently upgraded my next.js project to version 12.0.7, along with Typescript (4.5.4) and pdfjs-dist (2.11.228), among other libraries. Locally, everything runs smoothly with the commands yarn dev for development and yarn build for building. However, af ...

The negation operator in Typescript is failing to negate as expected

When a user changes a multiselect element, there is a function that runs to control the visibility of an error message: getVisibility(multiselect) { if ((multiselect.selectedCategories.length < 1 && !multiselect.allSelected) && th ...

Guide on displaying console.log in mobile simulator while using Angular2

Interested in debugging JavaScript on mobile devices, particularly Android and iPhone. Seeking a code snippet or library that can display console.log messages on the screen of a phone emulator. Ideally looking for a solution that works with angular2 and i ...

Is it possible for TypeScript to convert objects while preserving type annotations?

Apologies for my limited English skills, but I will do my best to explain my dilemma. I am looking to create a TypeScript function that can replace the keys of an Object. For example: interface Target { name: string; ID: number; } // The functio ...

Refreshing a page with a 404 error in Angular 2 while in production mode and without the useHash configuration

I've encountered an issue while using Angular 2 without the useHash feature. When trying to visit the URL directly in a browser, I'm getting a 404 not found error. I have searched extensively and attempted various solutions including: Adding L ...

What steps should I take to resolve this unexpected issue with svelte?

Whenever I attempt to execute the application, an error is consistently displayed to me. Here is a screenshot of the error: https://i.sstatic.net/jfo3X.png This issue always arises on the initial import type line, regardless of the content or arrangement ...

The Angular app.component.html is failing to display the newly added component

Having some trouble rendering my new component in the browser. I've set up a fresh project using the Angular CLI and created a component named list-employees. Upon running ng serve -o, the project compiles without errors, but the browser displays a b ...

Encountering a problem with Webpack SASS build where all files compile successfully, only to be followed by a JavaScript

Being a newcomer to webpack, I am currently using it to package an Angular 2 web application. However, I am encountering errors related to SASS compilation and the ExtractTextPlugin while working on my project. Here is a snippet from my webpack configurat ...

The properties required for type 'Subscription' are not present

I encountered an issue in my IDE while trying to run the following code. Within my component, I am making a call to a service in the ngOnInit method to fetch some data. This service, in turn, calls another service to gather additional information before f ...