【发布时间】:2022-01-22 00:38:26
【问题描述】:
您好,我尝试在 Angular 11 中进行反应式表单验证,但它在终端中显示以下错误。
错误TS2531 对象可能为空。
我在 register-form.component.ts 中的代码
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import {FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'app-register-form',
templateUrl: './register-form.component.html',
styleUrls: ['./register-form.component.css']
})
export class RegisterFormComponent {
title = 'Register Form';
angForm: FormGroup;
submitted = false;
constructor(private fb: FormBuilder) {
this.angForm = this.fb.group({
title: ['', Validators.required ],
name: ['', Validators.required ],
gender: ['', Validators.required],
address: ['', Validators.required ],
email: ['', Validators.required],
acceptTerms: [false, Validators.requiredTrue]
});
}
}
在 register-form.component.html 中
<div class="form-group ">
<label>Name:</label>
<input class="form-control" formControlName="name" type="text">
</div>
<div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['name'].errors['required']">
Name is required.
</div>
</div>
当我运行它的显示错误时
register-form.component.html:26:17 - 错误 TS2531:对象可能为“空”。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~【问题讨论】:
-
您的模板应该包含对“register-form.component.ts”中定义的 FormGroup 的引用:
标签: angular typescript validation