I subscribed to valueChanges of a mat-selection-list to be notified when the user selects a new list item. In some cases I ask the user if he/she really wants to select the new item via a confirmation dialog. If the user clicks "No" in this dialog, I need to cancel the selection of the new item. This is how I attempted to do this:
this.createForm.controls.selectionList.valueChanges.subscribe((value: number[]) => {
const prevValue = this.createForm.controls.selectionList.value;
if (<condition>) {
const confirmDialogRef = this.dialog.open(ConfirmationDialogComponent, {
data: "Do you really want to do this?",
});
confirmDialogRef.afterClosed().subscribe((confirmResult) => {
if (confirmResult === true) {
// User clicked yes, continue...
} else {
// User clicked no, set the previous value again...
this.createForm.controls.selectionList.setValue(prevValue, { emitEvent: false });
}
});
} else {
// No user confirmation required, just continue...
}
});
Unfortunately, this does not seem to work because prevValue seems to already be the new value when I try to set it as current value. What can I do instead to set the previous value again and basically just pretend that the user never even selected a new list item to begin with? Do I really have to cache the previous value manually, or is there a better way to do this?