'Passing multiple values from dialog in Angular 8
I have created a dialog using Material Design for Angular. In the original example there was only one field, which was bound with one parameter in parent view. I want to create a dialog, that gathers more than just one parameter and return these parameters back to the parent component, so I can post it to my API.
How it looks now:
<h1 mat-dialog-title>Create</h1>
<div mat-dialog-content>
<p>Fill in a new company name</p>
<mat-form-field>
<input matInput [(ngModel)]="data.name">
</mat-form-field>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">Cancel</button>
<button mat-button [mat-dialog-close]="data.name" cdkFocusInitial>Ok</button>
</div>
What I want to achieve:
<h1 mat-dialog-title>Create</h1>
<div mat-dialog-content>
<p>Fill in a new person name</p>
<mat-form-field>
<input matInput [(ngModel)]="data.name">
<input matInput [(ngModel)]="data.surname">
<input matInput [(ngModel)]="data.email">
<input matInput [(ngModel)]="data.mobile">
...
</mat-form-field>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">Cancel</button>
<button mat-button [mat-dialog-close]="WHAT DO I ENTER HERE?" cdkFocusInitial>Ok</button>
</div>
When I removed the [mat-dialog-close] property, the data never came back to the component and couldn't be sent to API. Could you advise on how do I pass back these multiple values?
Solution 1:[1]
The only thing you have to do is to send the data from the child (modal in this case) to the parent is to pass [mat-dialog-close]="data" in the button, The parent can take care of the values sent via the data object, if the values are correctly assigned.
<button mat-button [mat-dialog-close]="data" cdkFocusInitial>Ok</button>
and
data: {name: this.name, role: this.role}
See this StackBlitz for an example. Both values you added are being printed in the console and passed into the parent's component passedValues object, which is printed in the HTML file.
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log('All the data', result);
this.passedValues = result;
});
Solution 2:[2]
Imagine you have such case, in referring component you can easily use as you wanted
openDialog() {
this.dialog.open(AddChargesComponent, {
data: { name: this.name, surname:this.surname, email: this.email, mobile: this.mobile}
}).afterClosed().subscribe(response => {
console.log(response.name,response.surname, response.email, response.mobile )
})
}
Solution 3:[3]
In addition to Roy's answer, you can pass a subset of the data like this:
<button mat-button [mat-dialog-close]="{name: data.name, email: data.email}" cdkFocusInitial>Ok</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Roy |
| Solution 2 | Navruzbek Noraliev |
| Solution 3 | Cyril |
