Transferring JSON information from a dialog component to another component

In my application, I have 2 components named list and details, which are nested inside a parent component called customer. When the user clicks the delete button within the details component, a dialog window pops up like this:

https://i.sstatic.net/hd4t3.png

Upon clicking the delete button within the dialog window, an event named onDelete is triggered along with the associated JSON values. This allows me to reuse the onDelete function in other components.

HTML

 <p>Do you want to delete <span>{{data?.title}} ?</span></p>
   <br>
  <button (click)="onDelCustomer()">DELETE</button>

TS

 import { Component, Input , OnInit, Output, Inject, EventEmitter } from 
  '@angular/core';
 import {
    FormBuilder,
    FormControl,
    FormGroup,
    Validators,
   } from '@angular/forms';
   import {MAT_DIALOG_DATA} from '@angular/material';
    @Component({
      selector: 'app-delete',
      templateUrl: './delete.component.html',
      styleUrls: ['./delete.component.css']
     })
    export class DeleteComponent {
      @Input()
      public contact;

     @Output() public onDelete: EventEmitter<{}> = new EventEmitter();

     constructor(@Inject(MAT_DIALOG_DATA) public data: any,
        private fb: FormBuilder,) { }


      public onDelCustomer(): void {
       this.onDelete.emit(this.data); <==========
       console.log(this.data)
      }


    }

After logging the emitted JSON values in the delete component, I can see them successfully:

https://i.sstatic.net/Djrgl.png

However, when I attempt to log the same emitted values in the customer component, they do not appear. I am calling the emitted function like this:

  public onDelete() {
    this.someContact = this.data; <========
    console.log(this.someContact);
  }

DEMO

Updated code

Previously, I was handling the delete operation within the delete component itself as shown below:

  public onDelCustomer(): void { <============== code for deleting customer
    this.someContact = this.data;
    this.someContact.id = this.data.id;
    this.customersServiceList.deleteContact('00000000-11111-1111-0000000', 
    this.someContact, this.someContact.id);
  }

Now, I want to shift the delete operation to the customer component like this:

   public onDelete() {
    this.someContact = this.data;
    this.someContact.id = this.data.id;
    this.customersServiceList.deleteContact('00000000-11111-1111-0000000', 
     this.someContact, this.someContact.id);
  }

This change is aimed at transforming the delete component into a more generic component so that it can be reused effectively throughout the application.

Answer №1

Your data scope may have been lost due to the delete modal being activated with *ngIf and then removed from the DOM when a button is clicked. This causes the component to die and all of its properties (this) become undefined when trying to access data from another component via event emitter. To solve this issue, consider using a common service to communicate the delete message between components:

Create a common subject in a service, emit to this subject in the delete modal, and subscribe to it in the customer component.

Answer №2

To make the onDelete output event work in customer.component.ts, you need to subscribe to it. The event is triggered only when the delete button is clicked, so you should call the delete function of your customer component inside the subscription.

Here's an example of how to achieve this:

public initiateDeleteDialog($event: any): void {
  const dialogReference: MatDialogRef<DeleteComponent> = this.dialog.open(
    DeleteComponent,
    {
      width: "350px",
      data: $event
    }
  );
  
  // Subscribe to the onDelete event
  dialogReference.componentInstance.onDelete.subscribe(data => {
    console.log("Deleted Data: ", data);
    
    // Call the delete function of the customer component
    this.delete();
  });
}

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 causes @typescript-eslint to retain old types/files in its cache and prevent successful compilation?

When I kick off my Typescript application using tsc -b -w, I always encounter an issue with @typescript-eslint not reacting to file changes accurately. It flags invalid types/syntax errors where there are none. Restarting the process sometimes doesn't ...

Leveraging NgRx for Managing Arrays

export class Ingredient { public name: string; public amount: number; constructor(name: string, amount: number) { this.name = name; this.amount = amount; } } List of Ingredients: export const initialIngredients: Ingredient ...

Is there an RxJS trick to combine observables and manage state?

Currently encountering a common issue involving asynchronous execution, state management, and indentation complexities. Imagine a scenario where a REST call is made to add user information (user_info) to a user, notify their contacts of the change, and re ...

Developing a Typescript npm package

In my project, there is a directory called models (named my-models) which houses several important typescript classes for my application. While I have been able to use these classes within the app without any issues, I now wish to turn it into an npm pack ...

Utilizing TypeScript 3.1: Easier Array Indexing with Enums in Strict Mode

Enabling TypeScript "strict" mode with "noImplicitAny" causes this code to fail compilation. I am looking for guidance on how to properly declare and use Arrays indexed by Enum values. namespace CommandLineParser { enum States { sNoWhere, sSwitchValu ...

What are the advantages of using any type in TypeScript?

We have a straightforward approach in TypeScript to perform a task: function identity(arg) { return arg; } This function takes a parameter and simply returns it, able to handle any type (integer, string, boolean, and more). Another way to declare thi ...

Attempting to deactivate the submit button in the absence of any input

As a beginner trying to work with typescript and html, I am facing an issue with disabling the submit button when a user fails to enter a part number. The error message I am getting is "Cannot find name 'partNumber'". Any advice or guidance on th ...

There seems to be a malfunction with the routing feature in the src/index.html file

My routing setup is not functioning as expected in src/index.html angular. What I have is a header with some links for navigation: <header> <div class="logo"> <div class="logo-img-div"> <img src="../../ass ...

What is the best way to include rxjs in an npm library - as a dependency, peer dependency, or both?

After researching numerous posts and articles on dependencies versus peerDependencies, I am still not entirely certain what to do in my particular situation.... I have a library (which is published to a private npm repository) that utilizes rxjs; for exam ...

Display ion-item when selected in Ionic 3

Can anyone help me figure out how to display an item when a specific option is selected? I'm struggling to find a solution, so any assistance would be greatly appreciated. Thank you! <ion-item> <ion-label floating>Reward </ ...

The code inside the promise .then block is executing long before the promise has completed its

After spending quite some time working on this messy code, I finally have a functioning solution: loadAvailabilities() { let promises = []; let promises2 = []; let indexi = 0; //return new Promise((resolve, reject) => { this.appo ...

javascript/typescript - conditionally adding an item to an object

If I have an object called userData = {..} and I need to create another object, userDataB, with properties a, b, c, and d from userData but only if they are defined. One way to achieve this is by using the following approach: userDataB = {} if(userData.a ...

Angular - issue with subject observable not functioning as expected

In my service SelectorService, I have created a subject and an observable. private eventEligibleApiStatus = new Subject<any>(); public eventEligibleApiStatusUpdated$ = this.eventEligibleApiStatus.asObservable(); I also have a method in which I use s ...

What could be the reason for my router navigate function not functioning properly in Angular 8?

I need help with redirecting to another component in my Angular application. Currently, I have the following code: HomeComponent checkUrl(reference) { if (reference != this.ref) { this.router.navigate(['/еrror']); } } Thi ...

Having trouble integrating ColorThief with Angular, encountering issues with missing library methods?

I am attempting to integrate the Library ColorThief () into an Angular 12 project, but unfortunately, I have been unable to make it work. I started by running $ npm i --save colorthief and then in my desired component .ts file: const ColorThief = require ...

Error message thrown by node express.js indicating that response headers cannot be reset once they have been sent

As a newcomer to both node and express, I may be making a silly mistake. If you want to see the complete source code, please visit: https://github.com/wa1gon/aclogGate/tree/master/server logRouter.get("/loggate/v1/listall", function(req, res) { let ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Here's a way to resolve the issue: ReactDOM.render() - TS2345 error: Cannot assign type '() => Element' to type 'ReactElement' in the argument

After tackling React-Router with Typescript, I encountered a typing issue that has me perplexed. Prior to this, I was using an older version of React and React-Router. But now, after updating to the latest builds using yarn, I'm facing this hurdle. ...

Tips to enable cross-domain file downloads from Google Storage in Angular 5

We have integrated Videogular2 player (VG player) into our website to enhance the video viewing experience. Currently, we are looking to incorporate subtitles into one of our videos by using a subtitle file (.vtt) stored in Cloud Storage. However, when at ...

The template literal expression is invalid due to the "string | null" type when sending authorization

While working on implementing authorization, I encountered an error from Ts-eslint stating that there was an "Invalid type 'string | null' of template literal expression" when trying to execute the functionality. The data being retrieved from lo ...