gpt4 book ai didi

angular - 如何从 mat dialog 组件到实现 mat dialog 的组件进行通信?

转载 作者:太空狗 更新时间:2023-10-29 17:42:27 26 4
gpt4 key购买 nike

我有一个对话框组件和应用程序组件,其中实现了 Material 对话框。这是应用组件的代码

import { Component } from '@angular/core';
import {VERSION, MatDialog, MatDialogRef} from '@angular/material';
import { DialogComponent } from '../dialog.component';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 5';
DialogRef: MatDialogRef<DialogComponent>;
constructor(private dialog: MatDialog) {}
ngOnInit() {
}
addItem() {
this.DialogRef = this.dialog.open(DialogComponent);
}

receiveMessageFromDialogComponent() {
// how to receive message from dialog component
}
closeDialog(): void {
this.DialogRef.close();
}
}

对话框组件是实现表单的地方,我需要在这里获取表单值并接收它。我尝试使用 Angular 输入和输出来实现此目的,但由于没有 child 和 parent 的沟通,所以无法正常工作。 这是对话框组件

import { Component } from '@angular/core';

@Component({
template: `
<h1 mat-dialog-title>Add Item</h1>
<mat-dialog-content>
<mat-form-field class="example-full-width">
<input matInput placeholder="Item name here...">
</mat-form-field>
</mat-dialog-content>
<mat-dialog-actions>
<button mat-button (click)="saveMessage()">Add</button>
<button mat-button (click)="closeDialog()">Cancel</button>
</mat-dialog-actions>
`
})
export class DialogComponent {
saveMessage() {
console.log('how to send data to the app component');
}
closeDialog() {
console.log('how to close');
}
}

Working Example on StackBlitz

最佳答案

您实际上可以使用订阅 来实现通信 @Output通过MatDialogRef<DialogComponent> .对于某些场景,您可能需要在对话框关闭之前从对话框中获取数据。因此,我们不能使用 this.DialogRef.afterClosed()函数,因为我们必须先关闭对话框才能获取数据。相反,我们想要获取组件实例并从那里访问。

在您的 DialogComponent 上:

export class DialogComponent {

@Output() submitClicked = new EventEmitter<any>();

constructor(public dialogRef: MatDialogRef<DialogComponent>){}

saveMessage() {
this.submitClicked.emit('Your data');
}

closeDialog() {
this.dialogRef.close();
}
}

在您的AppComponent上:

openDialog() {
this.dialogRef = this.dialog.open(DialogComponent);
this.dialogRef.componentInstance.submitClicked.subscribe(result => {
console.log('Got the data!', result);
});
}

最好确保unsubscribe()你所有的Subscription秒。类似这样的操作可以快速取消订阅(如果不涉及数据验证):

const dialogSubmitSubscription = this.dialogRef.componentInstance.submitClicked
.subscribe(result => {
console.log('Got the data!', result);
// do something here with the data
dialogSubmitSubscription.unsubscribe();
});

此外,您始终可以通过 AppComponent 关闭对话框。与 this.dialogRef.close()如果必须的话。或者在上面的例子中,你也可以使用 this.DialogRef.componentInstance.closeDialog() .

关于angular - 如何从 mat dialog 组件到实现 mat dialog 的组件进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47952678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com