angular - 角度表单验证不显示错误消息
问题描述
如果密码或电子邮件无效,我正在运行登录表单以显示错误到目前为止,这就是我所拥有的
<form [formGroup]="loginForm" (ngSubmit)="SignIn(email.value, password.value)">
<mat-form-field>
<input formControlName="email" name="email" matInput type="text" placeholder="email">
</mat-form-field>
<mat-form-field>
<input formControlName="password" name="password" matInput type="password" placeholder="Password">
</mat-form-field>
<div *ngIf="errorCode" class="notification is-danger">
Email and password does not match
</div>
<div class="d-flex flex-column align-items-center">
<button mat-raised-button class="button is-success w-100" type="submit" [disabled]="!loginForm.valid">
Continue
</button>
</div>
</form>
在我的 ts
ngOnInit() {
this.loginForm = this.fb.group({
email: ['', [
Validators.required,
Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
]],
password: ['',
Validators.required
],
});
}
SignIn(email, password) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
.then((result) => {
this.ngZone.run(() => {
this.router.navigate(['dashboard']);
});
}).catch((error) => {
this.errorCode= error.message;
console.log(this.errorCode)
})
}
但是,当我提交无效用户时,似乎没有显示错误消息。以前我已经测试过
<div *ngIf="!loginForm.valid" class="notification is-danger">
Email and password does not match
</div>
但问题是它仅根据填充字段的位置显示,而不是验证字段本身。
解决方案
这是一个很长的镜头,但是,您将错误分配给组件,并且通常只有在您changeDetection: ChangeDetectionStategy.OnPush
在组件定义中声明时才会失败。如果是这样,您只需constructor(private cd: ChangeDetectorRef) {}
在块中分配错误值后注入更改检测器引用并使用它.catch
,如下所示:
}).catch((error) => {
this.errorCode= error.message;
console.log(this.errorCode)
this.cd.detectChanges();
})
推荐阅读
- ruby-on-rails - 我们如何获得传入 https 安全标头的自定义标头属性
- docker - Apache 重定向到 Docker 端口
- java - 应用程序更新后未显示 EULA 对话框
- c++ - 模板化函数中的模板不被解析为模板,而是作为比较
- android - 在 Android Pie (9.0) 上使用 CameraX 进行屏幕像素化
- reactjs - 如何根据我们要编辑的内容找到一个值
- c++ - 为什么标准关联有序容器允许 `const char*` 作为它们的键?
- android - 使用 livedata 获取 RecyclerView 的 ClickListener 时间
- windows - 有没有办法通过 Windows 命令观察文件的“可用性状态”?
- r - 如何在列表中保存多个饼图?