我有一个对话框表单,我想在用户按下转义键时优雅地关闭它。当用户按下转义键时,表单会立即关闭,但由于某种原因,对话框表单不会将结果发送到父表单。
通过取消按钮关闭时没有问题。
我已经在 userform
上使用“onKey”事件进行了尝试。组件,但这也不起作用。
在我的 typescript 和模板对话框文件中:
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
constructor(
private dialogRef: MatDialogRef<UpdateBonusConditieComponent>,
@Inject(MAT_DIALOG_DATA) private PassedData: ConditieTypeDialog,
) {} // I also tried it with a public PassedData instead of private
onCancel() {
console.log('komt ie hier');
this.PassedData.cancel = true;
}
onKey(event: any) {
this.onCancel();
console.log('toets ingedrukt ' + event.target);
}
onOK() {
console.log('OK button pressed');
}
<mat-dialog-content [formGroup]="dialogConditieForm"
(keyup)="onKey($event)">
</mat-dialog-content>
<mat-dialog-actions>
<button mat-button
color="accent"
(click)="onOK()"
[mat-dialog-close]="PassedData"
[disabled]="dialogConditieForm.invalid">Ok</button>
<button mat-button
color="warn"
(click)="onCancel()"
[mat-dialog-close]="PassedData">Cancel</button>
</mat-dialog-actions>
然后我有我调用对话框的父表单,一些细节:
import { MatDialog } from '@angular/material';
constructor(private matDialog: MatDialog) {}
const dialogRef = this.matDialog.open(UpdateBonusConditieComponent, {
data: {
onderwerpGUI: onderwerpGUI,
isNewRow: isNewRow,
cancel: false,
}
});
dialogRef.afterClosed().subscribe((result: ConditieTypeDialog) => {
if (result.cancel) { //when hitting escape result is undefined for some reason
this.selectedRow = null;
return 0;
}
});
我应该期待结果回来,以便
this.selectedRow
设置为 null
但如果使用转义键关闭对话框,则不会发生这种情况。我想我做错了什么。任何人都可以帮助我吗?
最佳答案
因为 onKey
对话框没有发送结果函数永远不会被调用。您可以改为订阅 keyboardEvents
在 MatDialogRef
并调用 onCancel
如果 Escape
被点击。我还为 backdropClick
添加了相同的内容因为那也是必需的。
constructor(
private dialogRef: MatDialogRef<UpdateBonusConditieComponent>,
@Inject(MAT_DIALOG_DATA) private passedData: ConditieTypeDialog,
) { }
ngOnInit() {
this.dialogRef.keydownEvents().subscribe(event => {
if (event.key === "Escape") {
this.onCancel();
}
});
this.dialogRef.backdropClick().subscribe(event => {
this.onCancel();
});
}
onCancel(): void {
this.passedData.cancel = true;
this.dialogRef.close(this.passedData);
}
onOK() {
console.log('OK button pressed');
}
此外,按照惯例,变量名使用驼峰命名 (
passedData
)。
关于angular - 如何在 Angular 对话框 Material 中的点击转义键上实现优雅关闭的表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57638210/