Angular项目报错:Error cannot read properties of null (reading '_rawValidators')求助
Angular报错:Error cannot read properties of null (reading '_rawValidators') 提交按钮无响应解决
我是编程新手,近期在Angular项目中遇到错误“Error cannot read properties of null (reading '_rawValidators')”,点击提交按钮后无任何响应。以下是对应的HTML模板及Component代码,无法明确问题根源,恳请技术帮助。
HTML代码
<h1> <span *ngIf="pageMode == pageModeEnum.Create">Add Customer</span> <span *ngIf="pageMode == pageModeEnum.Edit"> <span>Edit Customer </span> <span class="text-primary">{{ customer?.fullName }}</span> </span> </h1> <hr> <div class="row"> <div class="col-md-6"> <form [formGroup]="customerForm" (ngSubmit)="submitForm()"> <div class=""> <mat-form-field appearance="outline" class="w-100"> <mat-label>First Name</mat-label> <input matInput formControlName="firstName" required> <mat-error *ngIf="customerForm.controls['firstName'].hasError('required')">First name is required</mat-error> <mat-error *ngIf="customerForm.controls['firstName'].hasError('minlength') || customerForm.controls['firstName'].hasError('maxlength')"> First name must be between 3 and 16 characters long. </mat-error> </mat-form-field> </div> <div class=""> <mat-form-field appearance="outline" class="w-100"> <mat-label>Last Name</mat-label> <input matInput formControlName="lastName" required> <mat-error *ngIf="customerForm.controls['lastName'].hasError('required')">Last name is required</mat-error> <mat-error *ngIf="customerForm.controls['lastName'].hasError('minlength') || customerForm.controls['lastName'].hasError('maxlength')"> Last name must be between 3 and 16 characters long. </mat-error> </mat-form-field> </div> <div class=""> <mat-form-field appearance="outline" class="w-100"> <mat-label>Phone</mat-label> <input matInput formControlName="phone" required> <mat-error>Phone number is required</mat-error> </mat-form-field> </div> <div class=""> <mat-form-field appearance="outline" class="w-100"> <mat-label>Email</mat-label> <input matInput formControlName="Email" required> <mat-error>Email is required</mat-error> </mat-form-field> </div> <div class=""> <mat-form-field appearance="outline" class="w-100"> <mat-label>Gender</mat-label> <mat-select formControlName="gender"> <mat-option *ngFor="let gender of genderEnum | enumToArray " [value]="gender.index"> {{ gender.name }} </mat-option> </mat-select> </mat-form-field> </div> <div> <mat-form-field appearance="outline" class="w-100"> <mat-label>Date of birth</mat-label> <input matInput [matDatepicker]="picker" formControlName="dob"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> </div> <div> <button class="me-2" [routerLink]="['/customers']" mat-stroked-button color="basic">Cancel</button> <button mat-flat-button color="primary" type="submit"> <span *ngIf="pageMode == pageModeEnum.Create">Create</span> <span *ngIf="pageMode == pageModeEnum.Edit">Save</span> </button> </div> </form> </div> </div>
Component代码
import { HttpErrorResponse } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { Gender } from 'app/enums/gender.enum'; import { PageMode } from 'app/enums/pageMode.enum'; import { Customer } from 'app/models/customer.model'; import { CustomerService } from 'app/services/customer.service'; @Component({ selector: 'app-add-edit-customer', templateUrl: './add-edit-customer.component.html', styleUrls: ['./add-edit-customer.component.css'], }) export class AddEditCustomerComponent implements OnInit { customerId?: number; customer?: Customer; customerForm!: FormGroup; genderEnum = Gender; pageMode: PageMode = PageMode.Create; pageModeEnum = PageMode; constructor( private customerSvc: CustomerService, private activatedRoute: ActivatedRoute, private router: Router, private fb: FormBuilder) { } ngOnInit(): void { this.setCustomerId(); this.setPageMode(); this.buildForm(); if (this.pageMode == PageMode.Edit) { this.loadCustomer(); } } submitForm() { if (this.customerForm.valid) { if (this.pageMode == PageMode.Create) { this.customerSvc.createCustomer(this.customerForm.value).subscribe({ next: (customerFromApi) => { this.router.navigate(['/customers']); }, error: (error: HttpErrorResponse) => { console.log(error); } }); } else { this.customerSvc.editCustomer(this.customerId!, this.customerForm.value).subscribe({ next: () => { this.router.navigate(['/customers']); }, error: (error: HttpErrorResponse) => { console.log(error); } }); } } } //#region Private Methods private buildForm() { this.customerForm = this.fb.group({ id: [0], firstName: ['', Validators.compose( [Validators.required, Validators.minLength(3), Validators.maxLength(16)] )], lastName: ['', Validators.compose( [Validators.required, Validators.minLength(3), Validators.maxLength(16)] )], gender: ['', Validators.required], email: ['', Validators.required], dob: ['', Validators.required], phone: [] }); } private setCustomerId(): void { this.customerId = Number(this.activatedRoute.snapshot.paramMap.get('id')); } private setPageMode(): void { if (this.customerId) { this.pageMode = PageMode.Edit } } private loadCustomer() { this.customerSvc.getCustomer(this.customerId!).subscribe({ next: (customerFromApi : Customer) => { this.customer = customerFromApi; this.patchForm(customerFromApi); }, error: (error: HttpErrorResponse) => { console.log(error); } }); } private patchForm(customerFromApi: Customer) { this.customerForm.patchValue({ id: customerFromApi.id, firstName: customerFromApi.firstName, lastName: customerFromApi.lastName, gender: customerFromApi.gender, email: customerFromApi.email, dob: customerFromApi.dob, phone: customerFromApi.phone }); } //#endregion }
问题根源及修复方案
1. 表单控件名大小写不匹配(核心错误)
HTML中Email字段的formControlName="Email"是大写开头,但Component的buildForm方法里定义的是小写的email,Angular表单控件名是大小写敏感的,导致找不到对应控件,触发Error cannot read properties of null (reading '_rawValidators')错误,进而导致提交按钮无响应。
修复:将HTML中的Email输入框控件名改为小写:
<input matInput formControlName="email" required>
2. Phone字段验证不一致
HTML中Phone输入框加了required属性,但Component的formGroup里phone字段没有配置Validators.required,同时mat-error没有判断错误条件,会一直显示错误提示。
修复:二选一即可:
- 给Component的phone字段添加必填验证:
phone: ['', Validators.required] - 去掉HTML中Phone输入框的
required属性:<input matInput formControlName="phone">
同时完善mat-error的判断逻辑:
<mat-error *ngIf="customerForm.controls['phone'].hasError('required')">Phone number is required</mat-error>
3. Gender字段验证不匹配(可选优化)
Component中gender字段配置了Validators.required,但HTML的mat-select没有加required属性,建议保持一致:
<mat-select formControlName="gender" required>
内容的提问来源于stack exchange,提问作者user22629947
相关产品推荐
相关产品推荐

