错误 TS2531 对象在角度反应形式中可能为空 [英] error TS2531 object is possibly null in angular reactive forms
本文介绍了错误 TS2531 对象在角度反应形式中可能为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试在 angular 11 中进行反应式表单验证,但在终端中显示以下错误.
错误 TS2531 对象可能为空.
我在 signup.component.ts 中的代码
import {FormGroup, FormControl, Validators} from '@angular/forms';表单 = 新表单组({firstName: new FormControl('',Validators.required)})得到 f(){返回 this.form.controls;}
在 signup.component.html 中
</表单>
当我运行它的显示错误
必需">姓名为必填项!
错误 TS2531 对象可能为空.
解决方案
对象 f.firstName.errors
可以为 null.使用安全导航操作符?
:
*ngIf=f.firstName.errors?.required";
Hi i have tried to do reactive form validation in angular 11 but its showing following error in terminal.
error TS2531 object is possibly null.
my code in signup.component.ts
import {FormGroup, FormControl, Validators} from '@angular/forms';
form = new FormGroup({
firstName: new FormControl('',Validators.required)
})
get f()
{
return this.form.controls;
}
in signup.component.html
<form role="form" [formGroup]="form">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" formControlName="firstName" [ngClass]="{'is-invalid':form.get('firstName').touched && form.get('firstName').invalid}">
<div *ngIf="f.firstName.touched && f.firstName.invalid">
<small class="text-danger" *ngIf="f.firstName.errors.required">
Name is required!
</small>
</div>
</div>
</form>
when i run its showing error in
<small class="text-danger" *ngIf="f.firstName.errors.required"> Name is required!
error TS2531 object is possibly null.
解决方案
The object f.firstName.errors
can be null. Use the safe navigation operator ?
:
*ngIf="f.firstName.errors?.required"
这篇关于错误 TS2531 对象在角度反应形式中可能为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文