angularangular-materialmaterial-dialog

close material dialog from different component angular


I have component A which openes material dialog

component A

  openDialog(): void {
    const dialogRef = this.dialog.open(**component B**, {
      width: '1000px',
    });

then I use to load image in that dialog and with button upload I upload it using component B to the server. Now when I've finished uploading image I want to close that dialog from component B.

component B

onUpload() {
  const fd = new FormData(); 
  fd.append('image', this.selectedFile);
  this.service.uploadImage(fd).subscribe(
    (res:any)=>
    {
//how to close dialog here ?

    },

how can I do that ?


Solution

  • Dialog | Angular Material Documentation:

    Components created via MatDialog can inject MatDialogRef and use it to close the dialog in which they are contained. When closing, an optional result value can be provided. This result value is forwarded as the result of the afterClosed promise

    export class ComponentB {
      constructor(
        public dialogRef: MatDialogRef<ComponentB>
      ) {}
    
      onUpload(): void {
        // upload stuff
    
        this.dialogRef.close();
      }
    }