繁体   English   中英

为什么 angular 在 ngOnInit 中创建时说我的对象可以为空?

[英]Why is angular saying my object can be null when creating in ngOnInit?

在组件中创建表单:

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)]),
    })
  }

}

在 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>

对于 IDEA 出现的每一行,发誓

error TS2531: Object is possibly 'null'

我知道这是因为对象的创建发生在 ngOnInit 中。 放一个“?” 到处签名,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>

但它有多正确?

也许这个问题有更正确的解决方案?

也许我错误地创建了 Form Group 对象?

使用安全导航操作符检查控件验证的代码在逻辑上没有任何错误,因为它自 3.7 版以来一直在 TypeScript 中。

我注意到的另一件事是 HTML 中控件的重复获取。

将重复的this.form.get(..)调用移动到如下所示的 getter 中:

get email() {
  return this.form.get('email');
}

get password() {
  return this.form.get('password');
}

并且 HTML 脚本将更整洁,如 ? 运营商仍然一致:

<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM