![](/img/trans.png)
[英]Angular Reactive Forms - Validation Errors - Cannot read property of undefined or null
[英]Strange errors with Angular Reactive Forms Validation
我正在使用 Angular 7 在我的产品页面组件表单上测试一个简单的登录功能,但我遇到了这种奇怪的行为。 如果存在错误,我试图显示适当的验证消息,例如如果它不是有效的电子邮件,则应显示“必须是有效的电子邮件”消息,如果该字段留空,则“电子邮件是必需的”,应该会显示错误,当您开始输入时,所需的消息会消失,只显示有效的电子邮件错误消息。 这是我的代码。
添加product.component.html
所以现在我试图在错误存在但它不起作用时呈现跨度消息。
<form [formGroup]="loginForm" class="login-container" (ngSubmit)="login()">
<p>
<input class="form-control" type="email" placeholder="Email here" formControlName="email">
<span *ngIf="f.email.errors.required">email is required</span>
<span *ngIf="f.email.errors.email">must be a valid email</span>
</p>
<p>
<input class="form-control" type="password" placeholder="Password here" formControlName="password">
<span *ngIf="f.password.errors.required">Password is required</span>
</p>
<p><button type="submit" class="btn btn-md btn-primary">Submit</button></p>
</form>
添加product.component.ts
这是控制器,我尝试对验证规则使用短符号,但无济于事。
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-addproduct',
templateUrl: './addproduct.component.html',
styleUrls: ['./addproduct.component.css']
})
export class AddproductComponent implements OnInit {
loginForm:FormGroup;
isSubmitted:boolean = false;
constructor(
private router:Router,
private fb:FormBuilder
){}
ngOnInit() {
this.loginForm = this.fb.group({
email : ['', [Validators.required,Validators.email]],
password : ['', [Validators.required,Validators.min(6)]]
});
}
get f(){
return this.loginForm.controls;
}
}
我也将验证脚本更改为此但仍然无济于事
ngOnInit() {
this.loginForm = this.fb.group({
email : new FormControl('', [Validators.required,Validators.email]),
password : new FormControl('', [Validators.required,Validators.min(6)])
});
}
我收到这个错误
您在可能不存在错误的情况下检查是否存在错误。
你想要这样的东西:
f.email.errors?.required
甚至:
f.email?.errors?.required
对密码字段和第一次调用时该属性可能不存在的任何其他地方执行相同的操作。
你也可以使用
<span *ngIf="loginForm.hasError('required', ['password'])">Password is required</span>
在我看来,这要容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.