how to pass data from angular material dialog to parent component?

后端 未结 3 1795
时光取名叫无心
时光取名叫无心 2020-12-30 23:04

I\'m using angular 6 and I have a button which opens a dialog. in my dialog, I have a form that gets user\'s data and then I have two buttons to submit and cancel. I tried t

3条回答
  •  悲&欢浪女
    2020-12-30 23:48

    Send and Receive data from Dialog

    Dialog Component

    // HTML
    
    // Typescript export class DialogComponent { // receive data from parent using 'MAT_DIALOG_DATA' constructor(@Inject(MAT_DIALOG_DATA) public data: string, private dialogRef: MatDialogRef) { } cancel() { // closing itself and sending data to parent component this.dialogRef.close({ data: 'you cancelled' }) } confirm() { // closing itself and sending data to parent component this.dialogRef.close({ data: 'you confirmed' }) } }

    Parent Component

    constructor(private dialog: MatDialog) { }
    
    // method to open dialog
    openDialog() {
        let dialogRef = this.dialog.open(DialogComponent, {
          data: `Are you sure you want to delete?`
        })
    
        dialogRef.afterClosed().subscribe(res => {
          // received data from confirm-component
          console.log(res.data)
        })
    }
    

提交回复
热议问题