How can I dynamically pass attributes/parameters to openDialog function?

I am looking to dynamically pass the ID 59dc921ffedff606449abef5 to the MatDialog. Currently, I have hardcoded this ID for testing purposes.

Despite multiple attempts, I have been unable to successfully retrieve the ID dynamically for the function call. I even tried utilizing the @input feature without success.

edit-dialog.component.ts:

export class EditDialogComponent implements OnInit {
dialogResult:string = '';
constructor(public dialog:MatDialog, public loginService:LoginService ){ }
ngOnInit() {}
openDialog() {
    this.dialog.open(EditUserComponent, { data: '59dc921ffedff606449abef5' })
    .afterClosed()
    .subscribe(result => this.dialogResult = result);
}

}

edit-user.component.ts:

export class EditUserComponent implements OnInit {
    public message:any [];
    public resData: {};
    constructor(public thisDialogRef: MatDialogRef<EditUserComponent>, 
                  @Inject(MAT_DIALOG_DATA) public data: number, 
                  public loginService: LoginService) { }
      ngOnInit() {
          this.loginService.getSingleUser(this.data)
          .subscribe(data => {
              this.resData = JSON.stringify(data);
          })
      }
      onCloseConfirm() {
          this.thisDialogRef.close('Confirm');
      }
      onCloseCancel() {
          this.thisDialogRef.close('Cancel');
      }
}

The ID is retrieved from a JSON Response in the login-service.ts service:

getSingleUser(id) {
    return this.http.get(environment.urlSingleUsers + '/' + id, this.options)
    .map(res => {
        console.log('RES: ' + JSON.stringify( res.json() ) );
        return res.json();
    }).catch( ( error: any) => Observable.throw(error.json().error || 'Server error') );
}

extractData(result:Response):DialogUserData[] {
    return result.json().message.map(issue => {
        return {
            ID: issue._id,
            Email: issue.email,
            Name: issue.fullName
        }
    });
}

Below is where the openDialog() method is called:

<i class="material-icons" (click)="openDialog()">create</i>

For further clarification, here is an example of how the JSON Response appears:

"message": [
  {
    "_id": "59415f148911240fc812d393",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbb1bab5bef5bfb4be9bbdb4b4f5bfbe">[email protected]</a>",
    "fullName": "Jane Doe",
    "__v": 0,
    "created": "2017-06-14T16:06:44.457Z"
  },
  {
    "_id": "5943b80be8b8b605686a67fb",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f993969197d79d969cb99f9696d79d9c">[email protected]</a>",
    "fullName": "John Doe",
    "__v": 0,
    "created": "2017-06-16T10:50:51.180Z"
  }
]

Answer №1

I recently tackled a similar task, but I found the naming of components a bit confusing (it appears to be reversed).
One approach you could take is to fetch the user data first and then proceed to open the dialog in your main component:

edit-dialog.component.ts:

openDialog(id: string) {
  this.userService.retrieveUserData(id)
    .subscribe(user=> {
      const dialogRef = this.dialog.open(EditUserComponent, {
        data: user
      });

      dialogRef.afterClosed().subscribe(result => {
        console.log(`Dialog result: ${result}`);
      });
    });
}

You can then utilize the user data from the dialog to populate its view:

edit-user.component.ts:

ngOnInit() { 
  console.log(this.data);
}

This method allows for dynamic passing of user IDs:

<i class="material-icons" (click)="openDialog(id)">create</i>

Here, the id parameter can be an attribute of your main component.

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 utilize *ngSwitchWhen in a TypeScript environment?

I am currently working with Ionic2 and Angular2 and encountering an issue while trying to implement a segment using ngSwitchWhen. Unfortunately, the functionality is not working as expected and I am receiving an error message. How can I resolve this issue ...

Tips for serializing a dictionary that includes lists using Django-Restframework

Hey everyone, I'm working on a REST-API for my Django-App. I have a function that generates a list of dictionaries which I want to serialize and include in the API response. Here's a snippet of what the list (nodes_of_graph) looks like: [{' ...

Object containing properties for serializing to JSON format

I'm dealing with a class that has some internal properties and I want to convert them into json format. How can I achieve this? For example: public class Foo { internal int num1 { get; set; } internal double num2 { get; set; } public str ...

Ways to retrieve the key of an enum based on its value within Typescript

Here's an example of an enum: export enum Colors { RED = "RED COLOR", BLUE = "BLUE COLOR", GREEN = "GREEN COLOR" } Can you help me figure out how to retrieve the enum key based on a specific value? For instance, if I input "BLUE COLOR", ...

Issues with Angular Routes handling JSON array routes

Encountering an Issue with Angular Routing I'm relatively new to Angular and making good progress. I want Angular's routing functions to be dynamic so I created a small api for Angular to fetch from, returning an array. However, when I iterate o ...

Using JQuery to dynamically set dropdown option values from a JSON object

I have an HTML code snippet: $.ajax({ type: "POST", url: "hanca/hanca_crud.php", dataType: 'json', data: { id_hanca: id_hanca, type: "detail_hanca" }, //detail_hanca success: function(data) { var teks = ""; $.each( ...

The variable 'subscribe' is not recognized in the data type 'Subscription'

Using the GET method here to retrieve the list of applied jobs. This code snippet is taken from the appliedJobsPage. this.getjobs.getAppliedjobList().subscribe(data => { this.appliedjobs = data; }) This code is part of my provider page getJo ...

Issue with the scoring algorithm using Angular and Spring Boot

Hello, I have created a scoring algorithm to calculate scores, but I encountered an error in "salaireNet". ERROR TypeError: Cannot read properties of null (reading 'salaireNet') at ScoringComponent.calculateScore (scoring.component.ts:33:55) ...

Seeking out a particular key within a JSON object and then finding a match based on the id within that key's array - how can it be

Recently, I've been exploring JavaScript and encountering challenges when trying to apply array methods on objects. For instance, I received a fetch response and my goal is to extract the 'entries' key and then utilize the native Array.find( ...

updating dropdown menu options in angular

Is there a way to automatically refresh the select options for B whenever select A is changed? How can I achieve this in my code? //select A <select (change)="fasechange()" name="" [(ngModel)]="fase" id=""> ...

Unable to globally install @angular/cli using Node.js on Red Hat software collection

After installing node.js 8 from Red Hat Software Collection (rh-nodejs8), I encountered an issue where I couldn't globally install TypeScript or @Angular/CLI because my bash session was restricted by scl-utils, requiring admin rights for global instal ...

What is the process for generating the configuration files (tsconfig.json, typings.json, package.json)?

I have the ability to duplicate these files from the https://angular.io/guide/quickstart. However, I am eager to learn more about these specific files. Is it possible to create them manually? Where can I find additional information about these files? ...

TypeScript Styled Components

When utilizing styled-components with regular React.js, I am able to do the following: const Container = styled.div({ userSelect: `none !important`, }) However, when using TypeScript, I encounter an error: Argument of type '{ userSelect: string; ...

What is the best way to utilize the constructor in a JavaScript object so that only the properties within `this` are utilized?

I am looking to instantiate the following class: class Person { firstName; lastName; birthday; constructor(props: Person) { {firstName, lastName, birthday} = props } } var me = new Person({firstName: "donald", lastName: "trum ...

Expecting null in Angular2/Jasmine tests can lead to browser crashes

I'm currently experiencing issues with testing a particular component. Here is the test that I am running: describe('SmpEventsNewCompactEventComponent', () => { const specService: SmpSpecService = new SmpSpecService(); describe(&ap ...

Leveraging d3.js for Visualizations in an Angular2/Node/Express/MongoDB Application

I’m working on integrating d3.js (https://www.npmjs.com/package/d3) into my project, and upon loading the page, I encounter a ZoneAwareError. After executing npm install d3 --save, all dependencies were successfully installed. Although I followed the gui ...

The setting of the custom user agent in the Chrome Extension Manifest Version 3 is not functioning correctly

We currently have an extension that consists of only two files: manifest.json and background.js Despite the browser (Chrome version 112) not reporting any errors, we are facing an issue where the user agent is not being set to 'my-custom-user-agent&a ...

Is jest the ideal tool for testing an Angular Library?

I am currently testing an Angular 9 library using Jest. I have added the necessary dependencies for Jest and Typescript in my local library's package.json as shown below: "devDependencies": { "@types/jest": "^25.1.3", "jest": "^25.1.0", ...

Guide on how to access websocket data array using the Python-Binance library

I'm currently dealing with a script that utilizes websocket to receive JSON data from Binance and then prints it to the console using a callback function: {"e":"outboundAccountPosition","E":1600502318390,"u":16 ...

Error: SVG graphic fails to render in live platform environment

I am encountering a problem with viewing the svg elements in production mode, even though they worked perfectly fine in development mode (localhost). My team and I suspect that the issue lies with gulp. <img src="assets/logo.svg" alt="Log ...