dialogRef.close() is not a function opening from one component and closing from another component

1.3k Views Asked by At

I have below MatDialog

export class ImportProcessingDialog extends AppComponentBase {
    constructor(public dialogRef: MatDialogRef<ImportProcessingDialog>) {
        super(injector);
    }
    onCloseClick(): void{
        this.dialogRef.close();
    }
}

Now I am opening the MatDialog from one component as below

export class ImportDataComponent implements OnInit {
    constructor(private importProcesingDialog: MatDialog) {}
    private onClickImport() {
       this.importProcesingDialog.open(ImportProcessingDialog, {
           width: '30%'
       });
    }
}

Now I want to close the Dialog from Another component

export class RisksComponent {
    constructor(public dialogRef: MatDialogRef<ImportProcessingDialog>) {
    }

    oncloseClick(){
        this.dialogRef.close();
    }
}

When I do this, getting an exception as

NullInjectorError: R3InjectorError(MainModule)[MatDialogRef -> MatDialogRef -> MatDialogRef -> MatDialogRef]: 
  NullInjectorError: No provider for MatDialogRef!

So added the provider as below

 providers: [{
            provide: MatDialogRef,
            useValue: {}
          },]

With the provider code the error fixed however on I click on oncloseClick function getting below error

TypeError: this.dialogRef.close is not a function
1

There are 1 best solutions below

0
On BEST ANSWER

How about storing the dialog ref in a service, which can be accessed from any component!

export class ImportProcessingDialog extends AppComponentBase {
    constructor(public dialogRef: MatDialogRef<ImportProcessingDialog>, 
                private testService: TestService) {
        this.testService.dialogRef = dialogRef;
        super(injector);
    }
    onCloseClick(): void{
        this.dialogRef.close();
    }
}

Then on the risks component you can do

export class RisksComponent {
    constructor(public dialogRef: MatDialogRef<ImportProcessingDialog>,
                private testService: TestService) {
    }

    oncloseClick(){
        if(this.testService.dialogRef) {
            this.testService.dialogRef.close();
        }
    }
}