Search code examples
angulartypescriptangular-materialangular8material-dialog

Angular Material: Popup Window: Send Data to Parent while Window is Open and Button Click


How do I get value of an Angular Material Dialog Box, and send it to the Parent?

I know how to get data, after they Close the dialog box. Just curious how to get Data while the Dialog box is still open, or specifically when person is pressing button within Dialog box.

public openPropertySearchDialog(): void {
  const propertySearchDialogRef = this.propertySearchDialog.open(PropertyGridDialogComponent, 
  {
     width: '1500px',
     height: '950px',
     data: this.propertyList,
     hasBackdrop: false
   });
  
   propertySearchDialogRef.afterClosed().subscribe(result => {
     console.log('propertyResult', result);
   });
}

Update:

This will subscribe to data. Now I only need to know data when Button is Pressed inside Dialog component. Thinking of adding in another subscription for button press event, looking for clean way, instead of adding 2 subscriptions.

propertySearchDialogRef .componentInstance.propertyOutput.subscribe((data: any) => {
  console.log('test',data);
});

https://material.angular.io/components/dialog/api

Many Resources Online are when Window is Closed, looking for Open and Presses a button (which does not close dialog box)

How to pass data to afterClosed() in Angular Material Dialog in Angular 6

Pass several data from Mat Dialog Angular 4 back to parent


Solution

  • On your popup component , you can use an Output event emitter.

      onAdd = new EventEmitter();
      constructor() {
        
      }
      
      onButtonClicked() {
        this.onAdd.emit('test');
      }
    

    Inside the parent component ,

      openDialog() {
          const ref = this._dialog.open(InnerComponent);
          const sub = ref.componentInstance.onAdd.subscribe((data) => {
            console.log(data);
          });
          dialogRef.afterClosed().subscribe(() => {
            sub.unsubscribe();
          });
      }
    

    Here you are subscribing to the onAdd event.

    the event is emitted only when button is clicked, on your button (click) event , call onButtonClicked()