angular - 角度反应形式不显示错误消息
问题描述
我的反应式表单(Angular 11)出现错误。
当我想在我的输入电子邮件和密码尚未设置时显示错误消息,但我有一个错误 对象可能为空
我的 login.component.html
<div class="row mt-5">
<div class="col-md-6 mx-auto">
<form [formGroup]="loginForm">
<div class="form-group">
<label for="email">Email</label>
<input
formControlName="email"
type="text"
class="form-control"
id="email"
required
>
<div Class="text-danger">
<div *ngIf="loginForm.get('email').hasError('required')">Email is Required !</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
formControlName="password"
type="password"
class="form-control"
id="password"
required
>
<div Class="text-danger" >
<div *ngIf="loginForm.get('password').hasError('required')">Password is Required !</div>
<div *ngIf="loginForm.get('password').hasError('minlength')">Password was to be 8 Caracters !</div>
</div>
</div>
{{loginForm.value | json}}
<button [disabled]="loginForm.invalid" class="btn btn-primary btn-block">Sign In</button>
</form>
</div>
</div>
我的 login.component.ts
loginForm: FormGroup ;
constructor() { }
ngOnInit(): void {
this.loginForm = new FormGroup({
email: new FormControl(null, [Validators.required]),
password: new FormControl(null, [Validators.required, Validators.minLength(8)])
});
}
get email() { return this.loginForm.get('email'); }
get password() { return this.loginForm.get('password'); }
你能告诉我为什么我没有收到错误消息并且我有编译错误,称为Object is possible null。在 app.module.ts 文件中,我在导入部分有 formsModule 和 ReactiveModule。
解决方案
Try like as this -
In your Component just create one function and remove both which you have created for each control - email and password.
get inputRequired() { return this.loginForm.controls; }
In your HTML -
<div *ngIf="inputRequired.email.errors" class="text-danger">
<div *ngIf="inputRequired.email.errors.required">Email is Required !</div>
</div>
I have just shown you for Email, similarly you can do it for Password field too.
推荐阅读
- css - 取消最后一条CSS规则的效果
- python - 子命令和默认值的 Python argparse 顺序
- entity-framework - EF 不会使用 SQLite 从数据库生成每个模型
- r - 如何在已发布的 Power BI 上指示外部 R 代码的路径?
- sql - 从表1中获取值并在jsp中插入表2
- apache-spark - 具有组间聚合结果的 Pyspark 窗口
- flutter - 如何在 ListView ontap 中展开小部件?
- reactjs - 使用redux将多个api调用的响应从action发送到react js中查看文件
- python - time.process_time() 是否比 time.time() 更好地衡量性能?
- python - 将python中的有序dict转换为普通dict并提取值