Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to the parent component for API submission.

Current Setup:

<h1 mat-dialog-title>Create</h1>
<div mat-dialog-content>
  <p>Enter a new company name</p>
  <mat-form-field>
    <input matInput [(ngModel)]="data.name">
  </mat-form-field>
</div>
<div mat-dialog-actions>
  <button mat-button (click)="onNoClick()">Cancel</button>
  <button mat-button [mat-dialog-close]="data.name" cdkFocusInitial>Ok</button>
</div>

Desired Approach:

<h1 mat-dialog-title>Create</h1>
    <div mat-dialog-content>
      <p>Add details of a new person</p>
      <mat-form-field>
        <input matInput [(ngModel)]="data.name">
        <input matInput [(ngModel)]="data.surname">
        <input matInput [(ngModel)]="data.email">
        <input matInput [(ngModel)]="data.mobile">
        ...
      </mat-form-field>
    </div>
    <div mat-dialog-actions>
      <button mat-button (click)="onNoClick()">Cancel</button>
      <button mat-button [mat-dialog-close]="WHAT SHOULD GO HERE?" cdkFocusInitial>Ok</button>
    </div>

Removing the [mat-dialog-close] property resulted in the data not being returned to the component and preventing API submission. Can you provide guidance on how to pass back these multiple values?

Answer №1

To transfer data from a child (modal in this instance) to its parent, simply include [mat-dialog-close]="data" within the button element. The parent component can then handle the values passed through the data object if they are correctly assigned.

<button mat-button [mat-dialog-close]="data" cdkFocusInitial>Ok</button>

In addition,

data: {name: this.name, role: this.role}

Refer to this StackBlitz for a practical example. Both values that you input will be displayed in the console and transferred to the parent component's passedValues object, as shown in the HTML file.

dialogRef.afterClosed().subscribe(result => {
  console.log('The dialog was closed');
  console.log('All the data', result);
  this.passedValues = result;
});

Answer №2

Picture yourself encountering a scenario where you can effortlessly utilize the referring component as per your needs

    launchPopup() {
        this.popup.open(AddChargesComponent, {
          data: { name: this.name, surname:this.surname, email: this.email, mobile: this.mobile} 
        }).onClose().subscribe(result => {
          console.log(result.name,result.surname, result.email, result.mobile )
        })
      }

Answer №3

Building upon Roy's solution, another way to extract only a section of the information is by following this method:

  <button mat-button [mat-dialog-close]="{name: data.name, email: data.email}" cdkFocusInitial>Ok</button>

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 process for obtaining the complete URL using the getDownloadURL() function along with a token?

An error occurred due to an unresolved FirebaseStorageError: "storage/object-not-found". The message indicates that the object 'k91a73uzb99' does not exist in Firebase Storage. This type of error is categorized under FirebaseError with a code of ...

How to retrieve the ID of a parent sibling using jQuery DataTables

I have encountered a peculiar issue while trying to retrieve the ID of a table's parent sibling. Prior to initializing jQuery DataTables, obtaining the table's ID poses no problem. However, once it is initialized and the table is built, retrievin ...

What steps can I take to update this HTML document and implement the DOM 2 Event Model?

I'm struggling with converting my document from the DOM 0 Event model to the DOM 2 Event model standards. I've tried getting help from different tutors on Chegg, but no one seems to have a solution for me. Hoping someone here can assist me!:) P. ...

After the introduction of ReactiveFormsModule, the functionality of the Angular router has ceased

I am working on setting up a reactive form in Angular for a login page. Here is my login form: <form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)"> <div class="form-group"> <label for="username">Username</label> ...

Is it possible to utilize the $ symbol within the ngOnInit or constructor functions?

I recently encountered an issue while trying to use the dollar sign ($) in my constructor function, specifically within ngOnInit() and translate.instant. Here is a snippet of the code that caused the problem: declare var $: any; { var SelectedDevice = ...

Effortless link to a Gremlin database using a JavaScript app

I apologize for my lack of technical knowledge, but I am struggling to solve this issue despite studying the documentation. My goal is to establish a connection with a standard Gremlin DB (Cosmos) using gremlin. While it works well from the server, encoun ...

Angular2: Dynamically switch between selected checkboxes in a list

Is there a way to toggle a checked checkbox list in Angular2? I am trying to create a button that, when pressed while the full list is visible, will display only the checked items. Pressing the button again would show the entire list. Here's the Plu ...

Posting forms in NextJS can be optimized by utilizing onChange and keypress events for input fields

I am currently working on my first Edit/Update form within a newly created NextJs application as I am in the process of learning the framework. I seem to be facing an issue where the form constantly posts back to the server and causes the page to refresh ...

The ng-message function appears to be malfunctioning

I am facing an issue with the angularjs ng-message not working in my code snippet. You can view the code on JSfiddle <div ng-app="app" ng-controller="myctrl"> <form name="myform" novalidate> error: {{myform.definition.$error ...

Changing the structure of a JSON array in JavaScript

I'm currently developing an ExpressJS application and I need to send a post request to a URL. My data is being retrieved from a MS SQL database table using Sequelize, and the format looks like this: [ { "x":"data1", "y":& ...

"An ExceptionInInitializer error occurred - Can you provide more details,

An Issue Has Arisen: Exception in thread "main" java.lang.ExceptionInInitializerError at com.PoseidonTechnologies.caveworld.level.WoRe.<init>(WoRe.java:46) at com.PoseidonTechnologies.caveworld.CaveWorld.start(CaveWorld.java:80) at com.P ...

A lone function making two separate calls using AJAX

I have a function that includes two Ajax Get calls. Each call has a different function for handling success. function get_power_mgt_settings() { window.mv.do_ajax_call('GET',power_mgt.get_spin_down_url{},'xml',true,show ...

Strategies for breaking apart a large, monolithic Node.js JavaScript application

My node.js server application is expanding, and I am looking to split it into multiple files. Below is a snippet of the current monolithic server.js file: var express = require('express'); var app = express(); // other initialization code etc / ...

Update the html() function to include any content that has been typed into a

I have a webpage structured like this: <div id="report_content"> Some information <textarea name="personal"></textarea> <b>Other information</b> <textarea name="work"></textarea> </div> Whe ...

React is informing that the `toggleNode` prop is not recognized on this particular DOM element

I have encountered the following warnings in my app, which I believe are causing it to not load all its features properly. Warning: React is indicating that the toggleNode prop is not recognized on a DOM element. If you intend for it to be a custom attrib ...

What steps should I follow to obtain code coverage data in my Aurelia application with the help of karma?

After creating my Aurelia app using the Aurelia CLI (au new), I wanted to set up code coverage, preferably with karma-coverage, but was open to other options as well. First, I ran npm install karma-coverage --save-dev and then copied the test.js task over ...

Snapshots testing app Expo TypeScript Tabs App.tsx

After setting up an Expo project with Typescript and Tabs, I decided to add unit testing using Jest but ran into some issues. If you want to create a similar setup, check out the instructions here: . Make sure to choose the Typescript with Tabs option whe ...

Stop users from being able to input line breaks by pasting

I am currently facing a challenge with my code. Within the code, I have included a textarea where users can input the title of an article, and I want this title to be restricted to only one line. To achieve this, I created a script that prevents users from ...

Is your TypeScript spread functionality not functioning as expected?

I'm new to TypeScript, so please forgive me if I've made an error. On a guide about TypeScript that I found online, it states that the following TypeScript code is valid: function foo(x, y, z) { } var args = [0, 1, 2]; foo(...args); However, w ...

Solve the TypeScript path when using jest.mock

I am currently in the process of adding unit tests to a TypeScript project that utilizes compilerOptions.paths. My goal is to mock an import for testing purposes. However, I have encountered an issue where jest is unable to resolve the module to be mocked ...