0

The dialog should be closed when I call function close of MatDialogRef instance, but It doesn't.

I have a module called ShareModule, that contains HeaderCompose, and LoginComponent. HeaderComponent using LoginComponent to dialog.

<div class="HomeHeader-userinfo-2-nbm"><img class="HomeHeader-portrait-xqqY2"
            src="/assets/img/header-portrait.png"><span class="HomeHeader-login-D2hkS"
            style="color: rgb(253, 85, 83);"><span (click)="openDialog()">Login</span> | <span
                (click)="openDialog()">Register</span></span>
    </div>

TS:

constructor(public dialog: MatDialog) { }

openDialog(): void {
    const dialogRef = this.dialog.open(LoginComponent, {
      panelClass: 'custom-dialog-container',
      data: {name: 'alo', animal: 'dog'}
    });
    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
    });
  }

In LoginComponent I have a button like this:

<div class="Login-close-j_-2T" [mat-dialog-close]="true" (click)="onNoClick()"><img src="/assets/img/login-close.png"></div>

and TS:

constructor(public dialogRef: MatDialogRef<LoginComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) { }

onNoClick(): void {
    this.dialogRef.close();
  }

I import ShareModuel to a module called HomeModule and using HeaderComponent.

When I press a button the Dialog show, But when I press close button, It should be closed but It doesn't. I have tried [mat-dialog-close] but It still doesn't work.

quanchinhong
  • 142
  • 3
  • 18

1 Answers1

0

To close the dialog, You need to declare an event emitter before the constructor so that the function which opens the dialog knows when you've closed the dialog:

@Output() onChange = new EventEmitter()
constructor(public dialogRef: MatDialogRef<LoginComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) { }

onNoClick(): void {
    this.dialogRef.close();
  }

Also subscribe to the change in the dialogRef in the other TS:

const sub = dialogRef.componentInstance.onChange.subscribe(
      ()=>{
        this.ngOnInit() //or whatever you want to do after dialog closes 
      }
    )
Shashank Ks
  • 450
  • 5
  • 9
  • I want to close the dialog, what do you mean? – quanchinhong Jun 06 '21 at 07:37
  • You will need an event emitter is what I'm saying. dialogRef.afterClosed().subscribe(result => { console.log('The dialog was closed'); }); Put the second code block I've posted instead of this. – Shashank Ks Jun 06 '21 at 12:16