Angular Material — Dialog — Return Data
In the previous post, we looked at how to pass data to the dialog. In this post, we will look at how to allow the user to make a selection and then pass back the result to the parent component.
In this post I will show you how the user will load the dialog and then change the active status of the customer. and when the dialog closes, this will then pass the updated active status to the main component which will then update locally or on the server.
We can also update the server from the dialog when the user chooses an option and when closing the dialog, reload the data source behind the scenes but this is not the focus of this article.
To start, we will update the dialog HTML to add 2 buttons, we will only show one depending on the current activated status.
After the <p> tag in the <mat-dialog-content> we will add as follows
<button color="primary" *ngIf="!customer.active" (click)="activate()">Activate</button><button color="warn" *ngIf="customer.active" (click)="deactivate">Deactivate</button>
This will show only one of the buttons at any time depending on the current activated status.
Get Mo Gold’s stories in your inbox
Join Medium for free to get updates from this writer.
In the dialog component, we will add two methods, one to return true and one to return false . In the dialog component add the following code.
activate() { this.dialog.close(true);}deactivate() { this.dialog.close(false)}
When passing in a parameter into the close method, the main component can then listen for this and use the value returned. In the main component, we will update the show dialog as follows.
function showDialog(){
const dialog = this.dialogRef.open(ActivateCustomerConfirmComponent);dialog.afterClosed().subscribe((result: any) => { this.customer.active !== result ? this.customer.active = result : ""
});}
This updated method subscribes to the dialog and waits for the afterClosed() event and then subscribes to it. We then check if there is any change to the active state compared to the existing customer object and if there is we update the customer object.
As you can see from the above code snippet, it is very straight forwards to get a value returned from a dialog by adding a const variable to the dialog when initiating and then waiting for the afterClosed() method and then subscribing to the event which contains the returned value.
Cheers
Moshe






