要从MatDialog向父组件共享对象,可以使用EventEmitter来实现。以下是一个示例代码:
在父组件中,定义一个属性来接收从MatDialog传递的对象:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
从对话框接收到的对象:{{ receivedObject }}
`
})
export class ParentComponent {
receivedObject: any;
openDialog() {
// 打开MatDialog,并传递数据
const dialogRef = this.dialog.open(DialogComponent);
dialogRef.afterClosed().subscribe(result => {
this.receivedObject = result; // 接收从对话框返回的对象
});
}
}
在对话框组件中,定义一个Output属性并使用EventEmitter来发出事件,将对象传递给父组件:
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-dialog',
template: `
`
})
export class DialogComponent {
@Output() objectShared = new EventEmitter();
closeDialog() {
this.dialogRef.close();
}
shareObject() {
const object = { name: '对象名称', value: '对象值' };
this.objectShared.emit(object); // 发出事件,将对象传递给父组件
}
}
在父组件中,使用子组件的Output属性来监听事件,并在事件处理函数中接收从对话框传递的对象:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
从对话框接收到的对象:{{ receivedObject }}
`
})
export class ParentComponent {
receivedObject: any;
openDialog() {
// 打开MatDialog,并传递数据
const dialogRef = this.dialog.open(DialogComponent);
dialogRef.componentInstance.objectShared.subscribe(object => {
this.receivedObject = object; // 接收从对话框返回的对象
});
}
}
这样,当在对话框中点击"共享对象"按钮时,会将一个对象传递给父组件,并在父组件中显示出来。