Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Data from MdDialog in Angular Material 2

Tags:

I am using a MdDialogModule to show a Dialog window with an input field in it. The Modal is opening fine and I am able to enter text into input field and submit, but on clicking the Submit button, I want the data in the Input form to be returned to the Main Component that called the Dialog component and also close the Dialog.

How do I do this? I am able to pass data to MdDialog component, but didn't find any resource on how to return data to component from MdDialogComponent.

My Dialog component code looks like this

import { Component, OnInit, InjectionToken, Inject } from '@angular/core'; import { MD_DIALOG_DATA, MdDialogRef } from "@angular/material";  @Component({   selector: 'app-add-book',   templateUrl: './add-book.component.html',   styleUrls: ['./add-book.component.css'] }) export class AddBookComponent {    constructor() { }  } 

and the method in main component calling the dialog box looks like this. No response is being returned now, it returns Undefined as I haven't figured it out yet.

openCreateDialog() {     let dialogRef = this.dialog.open(AddBookComponent)       .afterClosed()       .subscribe(response => {         console.log(response);       });   } 
like image 246
Hisham Mubarak Avatar asked Aug 12 '17 08:08

Hisham Mubarak


People also ask

How do I get data from MatDialog?

You can pass any kind of data to the component by adding data to the MatDialog's open() options. }, }); You can retrieve the data by injecting MAT_DIALOG_DATA in the opened component.

What is$ mdDialog?

$mdDialog opens a dialog over the app to inform users about critical information or require them to make decisions. There are two approaches for setup: a simple promise API and regular object syntax.

How do I use MatDialog?

Approach: First we need to import 'MatDialog' from '@angular/material/dialog' and we need to create an instance for it in the constructor. Using this instance we can open the dialog box component. Now create a separate component for the dialog and write code as per the requirements.


Video Answer


2 Answers

First, you need to add MdDialogRef to your dialog component

export class AddBookComponent {   constructor(private dialogRef: MdDialogRef<AddBookComponent>) { } } 

Then use dialogRef.close to return the data

save() {   this.dialogRef.close({ data: 'data' }); } 
like image 154
Harry Ninh Avatar answered Oct 22 '22 19:10

Harry Ninh


Thanks for Harry's comment first...

below is the whole related script

Component ts:

  let dialogRef = this.dialog.open(DataListDialogComponent, dialogConfig).afterClosed()   .subscribe(response => {     console.log(response);   }); 

dialog ts:

    this.dialogRef.close({data:'data'}); 
like image 38
W Kenny Avatar answered Oct 22 '22 17:10

W Kenny