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 activating the quasar timepicker once a user has selected a time?

The functionality of the timepicker in Quasar doesn't quite meet my expectations. I don't want to add another library just for this feature. The main issue I have is that it doesn't close automatically after selecting a time. I managed to fi ...

Removing undefined elements from an array

Could somebody clarify why, in this particular scenario: const dataValues: ValueRange[] = res.data.valueRanges.filter((range: ValueRange) => range.values); const formattedValues: Array<SheetData | undefined> = dataValues.map(this.formatSheetRang ...

Suggestions to reduce our website loading time

Query: How can one effectively reduce the file size of a webpage to improve loading speed? What specific optimization practices and coding techniques (in JavaScript and PHP) can be implemented to decrease page weight? Motivation: After reading an article ...

Sending a PHP string formatted as JSON to be processed by jQuery

When attempting to echo a string with a JSON structure, I am encountering issues with the jQuery ajax post not parsing it correctly. My question is whether this string will be recognized as JSON by the jQuery json parse function when echoed in a similar ma ...

Activate the 'swipe back' feature within ion-item upon selecting ion-option-button

In my Ionic project, I created an ion-list with ion-items and added ion-option-buttons: <ion-list> <ion-item class="item " ng-repeat="exercise in exercises" on-double-tap="sendToChangeExercise"> <p><h2>{{exercise. ...

Navigating a jQuery collection using iteration

My goal is to loop through an array and set values to an element in the following manner: <tool>hammer</tool> var tools = ["screwdriver", "wrench", "saw"]; var i; for (i=0; i < tools.length; ++i){ $("tool").delay(300).fadeOut().delay(100). ...

The callback function is unable to access this within the $.post method

Hey there, I'm new to JavaScript/jQuery and I could use some help. I have an object prototype called Page that contains an array and a function for making an AJAX POST request and processing the response. Here's a snippet of the code: function P ...

Encountering a 500 internal server error or receiving an error message stating "invalid value for stripe.confirmCardPayment

I'm currently working on implementing a payment component for my React app using Stripe for the first time. Despite following a tutorial closely, I keep encountering an internal server error or receiving an "invalid value for stripe.confirmCardPayment ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

Issue: The specific module is unable to be located, specifically on the Heroku platform

While my application performs well locally and on a Travis CI build server, it encounters issues when deployed on Heroku. The error message Error: Cannot find module is displayed, leading to app crashes. Here are some details about the npm module: It r ...

Tips on extracting the image URL after uploading via Google Picker

I'm currently implementing the Google Drive File Picker on my website for file uploading. Everything seems to be working well, except I am facing an issue with retrieving the image URL for images uploaded through the picker. Below is my current JavaSc ...

Running the `npm build` command does not automatically execute the "build" script specified in the package.json file

I am exploring a new approach for my module by utilizing npm build instead of relying on gulp / Grunt or other specialized build tools. "scripts": { "build": "node build.js" }, The content of my build.js file is simply: console.log('Hello') ...

"Unraveling the Mystery: In Javascript Vue, what is the secret behind the origin of the variable 'e' found in the function

Where does the mysterious variable e in onFileChange(e) come from? In the code snippet below, we see a variable e being used in onFileChange(e). However, this variable is not declared or imported anywhere in the code. How is it possible for this to be val ...

Stop the form from being submitted using ajax if there are no values in the form fields

Having issues with a basic form. Struggling to prevent submission when fields are empty. Is there a straightforward way to validate the fields and stop the form from submitting? Below is the HTML form: <form method="post" name="simpleForm" id="simpleF ...

Incorporating an HTTP-based IFRAME into an HTTPS web address

My situation involves a PHP application running in HTTPS mode, within which there is an iframe containing an HTTP file. Both the parent and the iframe exist within the same domain. Strangely, I am unable to access the iframe source using HTTP. Is there a ...

Is it possible to activate the onChange event when the input value is being modified by the state with information obtained from a fetch

Currently, I am successfully fetching data from an API and storing it. However, I now want to incorporate a functionality where a user can paste a website URL into an input box, click a button, and then display the results in a return div UI. I am struggli ...

Top method for verifying email existence in ASP.NET database

In our current asp.net web application, we are facing some challenges with using the update panel on the user registration page to check for existing users. These issues include: 1- The update panel tends to slow down the process. 2- The focus is lost wh ...

Exploring the differences between importing all utilities as a whole using `import * as util from "./util"` and importing a specific function only with `import {someFunction

When comparing the two options of importing from a module, which is better: import * as util from "./Util" or import {someFunction} from "./Util"? ...

PhantomJS version 2.1.1 encountered an error on a Windows 7 system, displaying "ReferenceError: Map variable not found."

I've been utilizing the "MVC ASP.NET Core with Angular" template. I'm attempting to incorporate phantomJS and execute the tests, but encountering the following errors: ERROR in [at-loader] ..\\node_modules\zone.js\dist&bs ...

Enhance CKEditor with Linked Select Boxes Plugin

I have ventured into writing a CKEditor Plugin and have grasped the basic concepts. For instance: CKEDITOR.dialog.add( 'addDocumentGroupDialog', function ( editor ) { return { title: 'Link to a document group', min ...