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);       });   } 
                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.
$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.
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.
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' }); } 
                        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'}); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With