Pass information captured from Mat Dialog up to the main component

Looking for a way to pass true/false boolean data from a dialog box into the parent component without just console logging the result? You want to store it in a variable in the parent component for further use. Any suggestions on how to achieve this?

This is the code snippet of my parent component :

 openDialog( dialogData : any )
               {
    let dialogRef = this.dialog.open(DialogExampleComponent, {data : dialogData});

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

This is the HTML of my dialog component:

<h2 mat-dialog-title>Delete Element?</h2>
<mat-dialog-content>Are you sure you want to delete '{{dialogData.content}}'' from '{{dialogData.column}}'</mat-dialog-content>
<mat-dialog-actions>
    <button mat-button mat-dialog-close mat-dialog-close="true">Delete</button>
    <button mat-button mat-dialog-close mat-dialog-close="false">Cancel</button>
</mat-dialog-actions>

And here is the TypeScript code of my dialog component:

import { Component, OnInit,Inject } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';

@Component({
  selector: 'app-dialog-example',
  templateUrl: './dialog-example.component.html',
  styleUrls: ['./dialog-example.component.css']
})
export class DialogExampleComponent implements OnInit {

  constructor(@Inject(MAT_DIALOG_DATA) public dialogData : any) { }

  ngOnInit(): void {
  }

}

Answer №1

To close the dialog reference to the component, you must call the close function. In order to achieve this, you need to inject the reference. Here are the necessary steps:

//...
constructor(
  // Inject the dialog reference to the component
  public dialog: MatDialogRef,
  @Inject(MAT_DIALOG_DATA) public dialogData : any
) { }
//...

// Define a function to close the dialog with a boolean value
close(value: boolean) {
  return this.dialog.close(value);
}

Next, add a click listener to each button and invoke the close function.

<h2 mat-dialog-title>Delete Element?</h2>
<mat-dialog-content>Are you sure you want to delete '{{dialogData.content}}'' from '{{dialogData.column}}'</mat-dialog-content>
<mat-dialog-actions>
    <button mat-button (click)="close(true)">Delete</button>
    <button mat-button (click)="close(false)">Cancel</button>
</mat-dialog-actions>

Upon execution, the subscription will yield either true or false in the variable result.

UPDATE:

If you wish to bind the result to a class property, follow these steps:

//...
result: Observable<boolean> | undefined;

constructor(
  // Inject the dialog reference to the component
  public dialog: MatDialogRef,
  @Inject(MAT_DIALOG_DATA) public dialogData : any
) { }

openDialog(dialogdData: any) {
  // Assign the afterClosed result to the result property
  this.result = this.dialog
    .open(DialogExampleComponent, { data: dialogdData })
    .afterClosed();

  // You can then use the result property in your UI using *ngIf or subscribe to it.
}
//...

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

Experiencing a 404 ERROR while attempting to submit an API POST request for a Hubspot form within a Next.js application

Currently, I am in the process of developing a Hubspot email submission form using nextjs and typescript. However, I am encountering a couple of errors that I need help with. The first error pertains to my 'response' constant, which is declared b ...

Obtaining the ViewRef of the current component in Angular 4

How can I obtain the ViewRef for my current component? I am attempting to retrieve the ViewRef from a service. Below is the code: component.service.ts import { Injectable, ViewRef } from '@angular/core'; @Injectable() export class CheckboxSe ...

After the form submission, my Next.js component keeps rendering repeatedly in a cumulative manner

I am currently working on a memory game application using Next.js, Node.js, and Express.js. I seem to be encountering an issue specifically with the login page. Initially, there are no issues when submitting the form for the first time. However, after the ...

Triggering JSON schema validation event in React's Monaco Editor

I am interested in implementing custom JSON schema validation in my Monaco editor setup. Here is the current configuration: <MonacoEditor language="json" value={jsonValue} editorWillMount={(monaco) => { monaco.languages.json.jsonD ...

Error: Code cannot be executed because the variable "sel" has not been defined in the HTML element

Every time I try to click on the div, I encounter an error message stating 'Uncaught ReferenceError: sel is not defined at HTMLDivElement.onclick' I am currently developing with Angular 8 and this error keeps popping up. I have read through simil ...

Extract data from an HTTP request and assign it to variables using filter and map in Angular

I need to extract data from an http get request and assign it to 3 separate variables once fetched. Data: [ { reportId: 1, results1: [{ name: "TotalReferralsMade", optionId: 3082, factor: 1, description: null ...

There was an issue retrieving the token in the interceptor. The type 'Promise<void | Observable<HttpEvent<any>>>' does not match the expected type 'Observable<HttpEvent<any>>'

I am currently working on developing an interceptor that sends the token along with requests for the Api. In order to store user information, I am utilizing the @ionic/storage library. However, I am facing an issue where my interceptor cannot access the t ...

Initialization of an empty array in Typescript

My promises array is structured as follows: export type PromisesArray = [ Promise<IApplicant> | null, Promise<ICampaign | ICampaignLight> | null, Promise<IApplication[]> | null, Promise<IComment[]> | null, Promise<{ st ...

Creating a flexible TypeScript function handler that accepts optional arguments depending on the function's name

I am facing a challenge with defining the function type for running helper functions that prepare database queries. Some of these functions have arguments, while others do not. TS Playground Link type PreparedQuery = { query: string; params?: string[] ...

When I try to integrate Three.js into my React application, it mysteriously causes my root HTML element

While attempting to utilize Three.js in Typescript react, I successfully rendered a Dodecahedron figure along with random stars. However, my intention was to incorporate some markup into my Three.js scene using React. Unfortunately, when I render the Three ...

Employing the filter or find technique to extract an element contained within a JSON data structure

Is it possible to retrieve one of these items using the filter or find method to search for a match within the fiberAgrupations array? I attempted the following: const landlineRate = this.monolineJsonRates[0].cambioCaudal.getAll() .filter(landlinedRat ...

Tips on retrieving a value nested within 3 layers in Angular

In my Angular application, I have three components - A, B, and C. Component A serves as the main component, Component B is a smaller section nested inside A, and Component C represents a modal dialog. The template code for Component A looks something like ...

The unexpected behavior of rxjs withLatestFrom

import { of, Subject, interval } from 'rxjs'; import { tap, startWith, map, delay, publishReplay, publish, refCount, withLatestFrom, switchMap, take } from 'rxjs/operators'; const source$ = new Subject(); const res ...

Setting the default value for ngModel does not receive any information from the model

I am trying to populate a form with default values using the code below: <h3>ِStart Time</h3> <div class="row" > <div class="col"> <label for="startTime">Hour(s) </label> <input type="numb ...

Exploring how to read class decorator files in a Node.js environment

I've developed a custom class decorator that extracts permissions for an Angular component. decorator.ts function extractPermissions(obj: { [key: 'read' | 'write' | 'update' | 'delete']: string }[]) { re ...

Issue with interface result: does not match type

Hey there! I've been working on creating an interface in TypeScript to achieve the desired return as shown below: { "field": "departament_name", "errors": [ "constraint": "O nome do departam ...

How can we enhance intellisense to recognize instance members of an interface when using dynamic indices?

In the midst of developing an angular project, I am currently utilizing an interface to specify a configuration for a module. The design of the interface revolves around mapping names to objects and is relatively straightforward: export interface NamedRou ...

Exploring table iteration in Angular 7

I am looking to create a table with one property per cell, but I want each row to contain 4 cells before moving on to the next row... This is what I want: <table> <tr> <td> <mat-checkbox>1</mat-checkbox& ...

How to access elements by their class name in Angular

Recently, I encountered a situation with this specific span element: <span *ngFor="let list of lists[0].question; let i = index" id="word{{ i }}" (click)="changestyle($event)" class="highlight"> {{ list}} < ...

Guide on accessing a modal component in Angular?

I have an Edit Button on my component called SearchComponent. When the user clicks this button, it currently redirects them to another component named EditFormComponent using navigateByUrl('url-link'). However, I would like to enhance the user ex ...