【发布时间】:2018-10-18 06:38:39
【问题描述】:
我有一个登录对话框,想防止它在按下回车时自动关闭。
更具体地说,当用户输入凭据并按 Enter 并且凭据响应返回错误时,我希望对话框保留(这样我可以向他们显示一些错误消息并让用户再试一次) .
这就是我所做的:
export class LoginComponent {
constructor(public dialogRef: MatDialogRef<LoginComponent>) { }
onSubmit(): void {
this.authService.login(...)
.subscribe(res => {
...
},
error => {
this.dialogRef.disableClose = true;
}
}
}
this.dialogRef.disableClose = true; 仍然关闭对话框,即使响应返回为错误。
我应该怎么做?
编辑
login.component.ts
<mat-toolbar>
<span>Login</span>
</mat-toolbar>
<mat-card class="my-card">
<div *ngIf="error" style="color: red;">{{error}}</div><br />
<form (ngSubmit)="onSubmit()" [formGroup]="loginForm">
<mat-card-content>
<mat-form-field appearance="outline" class="full-width">
<mat-label>Email</mat-label>
<input matInput placeholder="Email"
formControlName="email"
[formControl]="emailFormControl"
[errorStateMatcher]="matcher" />
<mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
Enter valid email address
</mat-error>
<mat-error *ngIf="emailFormControl.hasError('required')">
Required field
</mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="full-width">
<mat-label>Password</mat-label>
<input matInput type="password"
placeholder="Password"
formControlName="password"
[formControl]="passwordFormControl"
[errorStateMatcher]="matcher" />
<mat-error *ngIf="passwordFormControl.hasError('required')">
Required field
</mat-error>
</mat-form-field>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button (click)="onNoClick()" color="primary">Close</button>
<button mat-raised-button
[disabled]="!(loginForm.controls.email.valid && loginForm.controls.password.valid)"
color="accent">
Login
</button>
</mat-card-actions>
</form>
</mat-card>
login.component.ts
onSubmit(): void {
if (this.loginForm.invalid) {
return;
}
this.authService.login(this.loginForm.controls.email.value, this.loginForm.controls.password.value)
.subscribe(res => {
if (res) {
alert("logged in");
}
},
error => {
this.error = 'Error! Plese try again.';
}
);
}
【问题讨论】:
-
MatDialog 默认情况下不会在用户按下回车键时关闭。必须使用 close() 函数故意关闭它。在您的代码中的某处,您正在关闭它。最初的焦点是否可能在您的取消/关闭按钮上?分享您的所有代码。
-
你是对的。最初的焦点是关闭按钮。我切换了两个按钮(关闭和登录)的顺序,它工作正常。我想这是最简单的方法。谢谢。
-
按钮顺序由材料设计指南指定,因此您应该始终遵循这些规则(右侧的肯定操作)。 MatDialogConfig autoFocus=false 让您最初没有任何焦点,因此在您的情况下这可能是一个更好的选择。
-
在
autoFocus=false之前,当我按下回车键时,它会关闭对话框。在我应用它之后,当我最初按 enter 时它不会关闭它,但是如果我输入一些输入并按 enter,即使响应返回为错误,它仍然会关闭对话框。 -
在验证输入有效或收到响应之前,您在代码中的某处关闭它。
标签: dialog angular6 angular-material-6