我已经使用Material Design for Angular创建了一个对话框。在原始示例中,只有一个字段,该字段在父视图中与一个参数绑定。我想创建一个对话框,该对话框不仅收集一个参数,而且将这些参数返回给父组件,因此可以将其发布到我的API中。
现在看起来如何:
<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>
我想要实现的目标:
<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>
当我删除[mat-dialog-close]
属性时,数据永远不会返回到组件,也无法发送到API。您能否建议我如何传回这些多个值?
想象您有这种情况,在引用组件时,您可以根据需要轻松使用它
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 )
})
}
您唯一要做的就是将数据从子级(在这种情况下为模态)发送到父级,是在按钮中传递[mat-dialog-close]="data"
,父级可以处理通过data
发送的值对象,如果已正确分配值。
<button mat-button [mat-dialog-close]="data" cdkFocusInitial>Ok</button>
和
data: {name: this.name, role: this.role}
请参见this StackBlitz为例。您添加的两个值都将在控制台中打印,并传递到父级的组件passedValues
对象,该对象打印在HTML文件中。
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log('All the data', result);
this.passedValues = result;
});