在Angular 8中,可以通过以下步骤将Angular Material对话框中的结果传递给其他组件:
MatDialog
和对应的对话框组件。例如,在app.component.ts
中引入MatDialog
和DialogComponent
:import { Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { DialogComponent } from './dialog.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(public dialog: MatDialog) {}
openDialog(): void {
const dialogRef = this.dialog.open(DialogComponent, {
width: '250px',
data: { name: 'John', age: 30 } // 传递给对话框的数据
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log('Dialog result:', result); // 在对话框关闭后获取结果
});
}
}
DialogComponent
,并在其中引入MAT_DIALOG_DATA
和MatDialogRef
:import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.css']
})
export class DialogComponent {
constructor(
public dialogRef: MatDialogRef<DialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {}
onNoClick(): void {
this.dialogRef.close();
}
}
dialog.component.html
中,可以通过双向绑定将对话框中的结果传递给其他组件。例如,将对话框中的输入框值传递给父组件:<h1 mat-dialog-title>Dialog</h1>
<div mat-dialog-content>
<p>Enter a value:</p>
<mat-form-field>
<input matInput [(ngModel)]="data.value">
</mat-form-field>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">Cancel</button>
<button mat-button [mat-dialog-close]="data.value" cdkFocusInitial>OK</button>
</div>
在这个例子中,对话框中的输入框值通过[(ngModel)]="data.value"
与data.value
进行双向绑定。当点击对话框中的"OK"按钮时,将data.value
作为结果传递给父组件。
这样,当对话框关闭时,父组件中的dialogRef.afterClosed().subscribe
方法中的result
参数将获取到对话框的结果。你可以在这个回调函数中处理结果,例如更新其他组件的数据或执行其他操作。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)、腾讯云云数据库MySQL(CDB for MySQL)、腾讯云对象存储(COS)。
腾讯云产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云