我的目标是如果按 Enter 键则执行 MatDialog 中的表单。关注哪个元素并不重要。我搜索了很多,尝试了很多东西,但每次都不起作用。
我尝试在表单上使用 ngSubmit,我在源 html 元素、mat-dialog-content-Element 和表单本身上初始化事件 keyup.enter。
所有路线都行不通。如果我为表单设置 keyup.enter-Event ,则仅当我聚焦表单字段并按 Enter 时才会触发它。如果我将此事件设置为源 html-element 或 mat-dialog-content-Element,则仅当我不聚焦表单时才会触发它。
我尝试创建一个 Stackblitz 但它不起作用,所以我只是分享代码:
打开 MatDialog 的组件:
TS
public openDialog() {
const dialogRef = this.dialog.open(EditUserComponent, {
width: '100%',
height: '100%',
});
}
HTML
<button mat-button (click)="openDialog()">Open Dialog</button>
打开的MatDialog:
HTML
<div class="flex-c justify-center full-height padding-l">
<label class="title-2">Create user</label>
<div class="flex-c full-size padding-l gap-l">
<div>
<form [formGroup]="formData" class="user-form">
<div>
<mat-form-field>
<mat-label>Name</mat-label>
<input type="text" matInput formControlName="name" />
</mat-form-field>
</div>
<div>
<mat-form-field>
<mat-label>Age</mat-label>
<input type="number" matInput formControlName="age" />
</mat-form-field>
</div>
</form>
</div>
<mat-dialog-actions>
<button mat-button color="warn" (click)="cancel()">cancel</button>
<button (click)="saveUser()" cdkFocusInitial>save</button>
</mat-dialog-actions>
</div>
</div>
TS
export class EditUserComponent {
public formData = new FormGroup({
name: new FormControl('', Validators.required),
age: new FormControl('', Validators.required),
});
constructor(public dialogRef: MatDialogRef<EditUserComponent>) {}
public cancel() {
this.dialogRef.close();
}
public save() {
if (this.formData.valid) {
console.log('User is updated');
}
}
}
我怎样才能做到这一点?
您尝试过使用@HostListener吗? HostListener 允许您捕获组件内部的事件。像这样的东西
export class EditUserComponent {
public formData = new FormGroup({
name: new FormControl('', Validators.required),
age: new FormControl('', Validators.required),
});
constructor(public dialogRef: MatDialogRef<EditUserComponent>) {}
@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (event.key === 'Enter') {
this.save();
}
}
public cancel() {
this.dialogRef.close();
}
public save() {
if (this.formData.valid) {
console.log('User is updated');
}
}
}