Passing data from a child component to a parent component in Angular 6 using MatDialog and EventEmitter

Currently able to establish communication between two components but unsure of how to pass the user-selected value as an Object via event emitter from the MatDialog component to the parent component. I aim to transmit the selected option's value and the text area's value as an object upon clicking the submit button.

dialog.html


    <mat-select [(ngModel)]="selectedIssue"  [ngModelOptions]="{standalone: true}">
        <mat-option  [value]="option1">Option AA</mat-option>
        <mat-option  [value]="option2">Option BB</mat-option>
        <mat-option  [value]="option3">Option CC</mat-option>
        <mat-option  [value]="option4">Option DD</mat-option>
        <mat-option  [value]="option5">Option EE</mat-option>
    </mat-select>

    <div>
        <textarea class="mention-reason" [(ngModel)]="reason" [ngModelOptions]="{standalone: true}"></textarea>
    </div>

    <button class="cancel" matDialogClose>Cancel</button>      
    <button class="submit" [mat-dialog-close] (click)="submitUserReason()">Submit</button></span>

dialog.ts


onSubmitReason = new EventEmitter();
submitUserReason(): void {
    this.onSubmitReason.emit('hello');
}

onConfirmClick(): void {
    this.dialogRef.close(true);     
}

parent.ts


callSupport() {
    const dialogRef = this.dialog.open(customerSupportComponent);
    const subscribeDialog = dialogRef.componentInstance.onSubmitReason.subscribe((data) => {
        console.log('dialog data', data);
        //i can see 'hello' from MatDialog
    });

    dialogRef.afterClosed().subscribe(result => {      
        subscribeDialog.unsubscribe();
    });

Appreciate any assistance provided.

Answer №1

Assuming there are a pair of buttons - 1) submit and 2) close

If you wish to retrieve selected data in the parent component upon clicking the submit button, then,

submitUserDetails(): void {
   this.dialogRef.close({ option: userSelectedOption, reason:userReason });
}

Subsequently, in the parent component,

this.dialogRef.afterClosed().subscribe(result => {
console.log(result);
});

Answer №2

If you're working on your dialog.ts file, it's important to pass more than just a string when submitting user reasons. You can do something like this:

submitUserReason(): void {
   this.onSubmitReason.emit(selectedIssue);
}

Don't limit yourself to passing only one piece of data - consider passing an object with multiple values too:

submitUserReason(): void {
   let data = { issue : selectedIssue, reason: userReason};
   this.onSubmitReason.emit(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

Leveraging both closetag.js and closebrackets.js simultaneously in Codemirror on a single line

Currently, I am integrating the Codemirror library with a textarea to enable autoclosing of HTML tags and brackets such as {}, (), []. However, I have come across an issue where they do not work together on the same line. For example, when typing out a ta ...

"Looking to access your Express app in a VM from the internet? Here's how

I have an express app running on a Node.js server hosted on Azure Linux VM, and I am looking to access this website from my personal computer. const express = require('express'); const app = express(); app.listen(3000, () => { console.lo ...

What is the best way to display data from a dynamically generated table in a popup window?

My table is dynamically populated with the following JavaScript code: $(document).ready(function (e) { var t = { Qty: [61.0, 0.0, 8.0], Name: ["2009 A", "2009 B", "2009 C "] } $.each(t.Qty, function (i, ele) { $("#content") ...

Having issues executing a conditional check using ng-if in AngularJS

I am attempting to verify a condition and here is how it appears: <ons-list-item ng-repeat="EventList in EventLists" ng-if="EventList.start.dateTime | DateMonth == TodayDetail"> I am encountering difficulties with this ng-if="EventList.start.dateTi ...

What is the process for adding parameters to a Fetch GET request?

I have developed a basic Flask jsonify function that returns a JSON Object, although I am not certain if it qualifies as an API. @app.route('/searchData/<int:id>',methods=["GET"]) def searchData(id): return jsonify(searchData(id)) Curr ...

Exploring React: Opening a new page without rendering the SideBar component

I currently have an application with a sidebar that navigates to three different pages, all of which include a navigation bar and the sidebar. However, for the next page I want to exclude the sidebar but still include the navigation bar. How can I configur ...

Combining Objects within an Array in JavaScript When Certain Conditions Are Satisfied

In my scenario, I am seeking assistance with merging the values of objects in an array if the id matches the warehouse_item_id. Specifically, there are two objects that need to be merged: id 191 and id 52 because id 52 has a warehouse_item_id of 191. Ple ...

Issues arise with the functionality of Zurb Foundation 5 tabs

Utilizing the tabs feature in ZURB Foundation 5, I've noticed that clicking on a tab changes the hash in the URL. However, I actually want to prevent this behavior as I rely on the hash for managing page loads. Although I attempted to use preventDef ...

Merge JavaScript files from various folders using grunt's configuration settings

I am currently working with Grunt and Sass, and I am in search of a SASS-like feature that will allow me to import any JavaScript file I desire and merge them into a single file based on some configuration depending on the directory I am in. For instance, ...

Use JQuery to gradually decrease the opacity of divs individually

I am currently working on a function that fades out all divs except the one that has been clicked on simultaneously. However, I want them to fade out one by one instead. Additionally, I would like the divs to fade out in a random order. If anyone knows ho ...

What is the reason for the retrieval of jquery-3.5.1.min.js through the request.params.id expression?

For my school project, I am using Express.js with TypeScript to create a simple app. This router is used for the edit page of a contact list we are developing. It displays the ID of the current contact being edited in the search bar. The problem arises whe ...

Saving data in a CSV file on your local device using HTML5

Is it possible to utilize HTML5 for saving or writing data to a local file on the user's file system? I am curious about this functionality, especially since HTML5 now offers the capability to export data from the client and save it as a CSV file. If ...

The functionality of this.router.navigate in Angular 15 seems to be off, as it is throwing an error saying it is not

Just have a quick question: Check out this code snippet... import { DOCUMENT } from '@angular/common'; import { Component, HostListener, Inject, NgZone } from '@angular/core'; import { Router } from '@angular/router'; @Compo ...

Exploring Database with NodeJS, Express, and HTML

My goal is to create a basic web application using node.js where users can input data into a search bar and have that input sent to the server for database query. While I've successfully set up and connected my database, here's a glimpse of my co ...

Tips for maintaining the original Backbone template when reloading the browser

Within my Backbone application (with a Rails backend), I utilize [Handlebars] JavaScript templates (JST's) to render the Backbone views. However, whenever I refresh the browser while on a URL template, it always redirects me back to the root URL. I am ...

The attempted creation of the ui.tree module failed with the error: [$injector:nomod] Unable to find module 'moduleName'! This could be due to a misspelling of the module name or

In my AngularJS project, I am utilizing a third-party library called angular-ui-tree to display data. To integrate this library, I need to include ui.tree as a dependency in my main app module. Following the instructions provided in the link, I have succes ...

Converting MongoDB Queries to MySQL in Node: A Step-by-Step Guide

I am currently facing a challenge where I need to migrate my app's database from mongoDB to mysql. The application was initially developed using node.js, but I encountered an issue with the "Create table" query while attempting the conversion process. ...

API response containing JSON data is not being displayed properly in the webdatarocks angular component

I can't seem to figure out how to properly display the JSON formatted data returned by a REST API using Angular. Any suggestions on how to accomplish this? Here's what I've been attempting to do - fetchData() { this.service.fetchData().s ...

Add each individual item from the array into the database sequentially

I have a collection of data entries that I need to individually insert into the database, like so: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] In essence, I plan to use a for..of loop to iterate over this array and add them one by one. If ...

Using JavaScript to set the value of an input field based on the selected option value

I'm attempting to display the value of the selected OPTION in a separate INPUT FIELD, but for some reason it's not working and I can't figure out what's causing the issue. Here’s the code snippet: <!doctype html> <html lan ...