[英]Why is angular saying my object can be null when creating in ngOnInit?
Creating a form in the component:在组件中创建表单:
export class LoginPageComponent implements OnInit {
form!: FormGroup
constructor() { }
ngOnInit() {
this.form = new FormGroup({
email: new FormControl(null, [Validators.required, Validators.email]),
password: new FormControl(null, [Validators.required, Validators.minLength(6)]),
})
}
}
In html, I perform value input checks在 html 中,我执行值输入检查
<div *ngIf="form.get('email').touched && form.get('email').invalid" class="validation">
<small *ngIf="form.get('email').errors.required">Enter Email</small>
<small *ngIf="form.get('email').errors.email">Enter valid Email</small>
</div>
For every line where the form IDEA occurs, swears对于 IDEA 出现的每一行,发誓
error TS2531: Object is possibly 'null'
I understand that this is due to the fact that the creation of the object takes place in ngOnInit.我知道这是因为对象的创建发生在 ngOnInit 中。 Put a "?"
放一个“?” sign everywhere and IDEA stops swearing:
到处签名,IDEA 不再骂人:
<div *ngIf="form.get('email')?.touched && form.get('email')?.invalid" class="validation">
<small *ngIf="form.get('email')?.errors.required">Enter Email</small>
<small *ngIf="form.get('email')?.errors.email">Enter valid Email</small>
</div>
But how correct is it?但它有多正确?
Maybe there is a more correct solution to this problem?也许这个问题有更正确的解决方案?
Maybe I'm creating the Form Group object incorrectly?也许我错误地创建了 Form Group 对象?
There is nothing logically wrong with the code for checking the control validations using the safe navigation operator, as it has been in TypeScript since version 3.7.使用安全导航操作符检查控件验证的代码在逻辑上没有任何错误,因为它自 3.7 版以来一直在 TypeScript 中。
One other thing I noticed is the repeated gets for the controls in the HTML.我注意到的另一件事是 HTML 中控件的重复获取。
Move the repeated this.form.get(..)
calls into getters like below:将重复的
this.form.get(..)
调用移动到如下所示的 getter 中:
get email() {
return this.form.get('email');
}
get password() {
return this.form.get('password');
}
and the HTML script will be tidier as shown with the ?并且 HTML 脚本将更整洁,如 ? operator still consistent:
运营商仍然一致:
<div *ngIf="email?.touched && email?.invalid" class="validation">
<small *ngIf="email?.errors.required">Enter Email</small>
<small *ngIf="email?.errors.email">Enter valid Email</small>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.