要在Angular Material的matdialog中更新主页面中的值,您可以使用matdialog的“afterClosed”事件来获取对话框的返回值,并在主页面中更新相应的值。
下面是一个示例代码,演示了如何在matdialog中更新主页面中的值:
在主页面中的HTML模板:
Value: {{ value }}
在主页面的组件类中:
import { Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MyDialogComponent } from './my-dialog/my-dialog.component'; // 对话框组件
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
value: string;
constructor(public dialog: MatDialog) {}
openDialog(): void {
const dialogRef = this.dialog.open(MyDialogComponent, {
width: '250px',
data: { value: this.value } // 将当前值传递给对话框
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.value = result; // 更新主页面中的值
}
});
}
}
在对话框组件中的HTML模板:
Dialog
Current value: {{ data.value }}
在对话框组件的类中:
import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'app-my-dialog',
templateUrl: './my-dialog.component.html',
styleUrls: ['./my-dialog.component.css']
})
export class MyDialogComponent {
constructor(
public dialogRef: MatDialogRef,
@Inject(MAT_DIALOG_DATA) public data: { value: string }
) {}
onNoClick(): void {
this.dialogRef.close();
}
}
在对话框组件中,我们使用了双向绑定 [(ngModel)] 来更新对话框中的值,并在点击"Save"按钮后将新值传递回主页面。在主页面的组件类中,我们订阅了matdialog的“afterClosed”事件,并在其中更新主页面中的值。
通过这种方式,您可以在matdialog中更新主页面中的值。