简体   繁体   中英

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

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

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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM