错误TS2531对象在角度反应形式中可能为空
嗨,我尝试在 angular 11 中进行反应式表单验证,但它在终端中显示以下错误。
错误 TS2531 对象可能为空。
我在 signup.component.ts 中的代码
import {FormGroup, FormControl, Validators} from '@angular/forms';
form = new FormGroup({
firstName: new FormControl('',Validators.required)
})
get f()
{
return this.form.controls;
}
在 signup.component.html 中
<form role="form" [formGroup]="form">
<div>
<label>Name</label>
<input type="text" name="name" formControlName="firstName" [ngClass]="{'is-invalid':form.get('firstName').touched && form.get('firstName').invalid}">
<div *ngIf="f.firstName.touched && f.firstName.invalid">
<small *ngIf="f.firstName.errors.required">
Name is required!
</small>
</div>
</div>
</form>
当我运行它的显示错误时
<小班= “TEXT-危险” * ngIf = “f.firstName.errors。需要”>名称是必需的!
错误 TS2531 对象可能为空。
回答
该对象f.firstName.errors可以为空。使用安全导航操作符?:
*ngIf="f.firstName.errors?.required"
- Or `f.firstName.hasError('required')` or `f.hasError('required', 'firstName')`.