3

I have a dialog with yes and no options(confirmation box). I want to wait till the user press yes or no button from dialog, but right now on button click, even before clicking the options in dialog box, console log prints initial/empty string.

HTML:

<button (click)="foo()"></button>

Component:

selectedOption = '';

foo() {
  this.openDialog();
  console.log('selectedOption: ' + this.selectedOption); // Prints initial Value
  // hit the API if selectedOption is yes.
}

openDialog() {
  dialogRef.afterClosed().subscribe(result => {
    this.selectedOption = result;
  });
}
Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
Malik Shahzad
  • 6,703
  • 3
  • 37
  • 49

1 Answers1

1

It has to do with the way you wrote the code and the fact the afterClosed returns an Observable asynchronously. After the call to this.openDialog(); you are calling console.log(....); At this point the selectedOption is still empty because you initialized it at the top to an empty string.

Just move the console.log and the api logic to the the subscribe block:

selectedOption = '';

foo() {
  this.openDialog();
}

openDialog() {
  dialogRef.afterClosed().subscribe(result => {
    this.selectedOption = result;
    console.log('selectedOption: ' + this.selectedOption); // Prints 
    // hit the API if selectedOption is yes.
  });
 }
Frederik Struck-Schøning
  • 12,981
  • 8
  • 59
  • 68
Gilad S
  • 1,753
  • 1
  • 13
  • 14