Reputation: 5733
I use Angular Material in my application and also Angular Material dialogs. After closing a dialog either action A or action B should be executed depending on the button clicked:
dialogRef.afterClosed().subscribe(() => {
// if close button was clicked do action A
// if other button was clicked do action B
})
Is there a possibility to detect which button was clicked in afterClosed method?
Upvotes: 9
Views: 9111
Reputation: 1826
The way that I currently using is to pass an string from dialog while closing like :
this.dialogRef.close('A or B or whatever');
and I use them outside like this :
dialogRef.afterClosed().subscribe((result: any) => {
if (resuld === 'A'){
// if close button was clicked do action A
} else if (resuld === 'B') {
// if other button was clicked do action B
}
})
Upvotes: 3
Reputation: 16837
You can close the dialog with custom data. Like this:
in your dialog component:
@Component({/* ... */})
export class YourDialog {
constructor(public dialogRef: MatDialogRef<YourDialog>) { }
closeA() {
this.closeDialog('A')
}
closeB() {
this.closeDialog('B');
}
closeDialog(button: 'A' | 'B') {
this.dialogRef.close(button);
}
}
handle close like this:
dialogRef.afterClosed().subscribe(result => {
if (result === 'A') {
// handle A button close
}
if (result === 'B')
// handle B button close
}
});
And since afterClosed()
is an observable, you can filter this stream to create a more declarative solution:
const closedA$ = dialogRef.afterClosed().pipe(filter(result => result === 'A'));
const closedB$ = dialogRef.afterClosed().pipe(filter(result => result === 'B'));
closedA$.subscribe( // handle A);
closedB$.subscribe( // handle B);
Upvotes: 14