You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular页面加载报错TypeError: Cannot read properties of null (reading '_rawValidators')

解决Angular表单错误:TypeError: Cannot read properties of null (reading '_rawValidators')

错误原因分析

你的代码核心问题是混合使用了Reactive Forms(formControlName)和模板驱动表单(ngModel)但未正确配置,同时存在事件绑定错误:

  1. 输入框同时使用formControlName和[(ngModel)],Angular无法正确关联表单控件与FormGroup,导致找不到对应控件抛出空指针错误;
  2. <select>标签使用了错误的(select)事件,该事件用于文本选中,而非选项变更;
  3. 初始wifiSelected为空对象,auth属性未定义可能导致隐藏逻辑异常。

修复方案(统一使用Reactive Forms)

1. 修改组件代码

移除冗余的ssid、psk变量,直接通过FormGroup控件操作数据:

import { Component, OnInit } from '@angular/core';
import { Wifi } from './wifi';
import { WifiService } from './wifi.service';
import { FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'angular-esp';

  datalist: Array<Wifi> = [];
  wifiSelected : Wifi = {} as Wifi;

  checkoutForm = this.formBuilder.group({
    ssid: [''],
    psk: ['']
  });
  
  constructor(private wifiservice: WifiService, private formBuilder: FormBuilder) { }

  ngOnInit()
  {
    this.wifiservice.getWifiList().subscribe(wifilist => this.datalist = wifilist);
  }

  selected(){
    if(this.wifiSelected?.ssid){
      this.checkoutForm.get('ssid')?.setValue(this.wifiSelected.ssid);
    }
  }

  onSubmit(): void {
    this.wifiservice.connect(this.checkoutForm.value).subscribe();
  }
}

2. 修改HTML模板

移除所有[(ngModel)],修正事件绑定,并为独立的wifiSelected控件配置ngModelOptions:

<form [formGroup]="checkoutForm" (ngSubmit)="onSubmit()">

<div class="section">
  <select [(ngModel)]="wifiSelected" (change)="selected()" [ngModelOptions]="{standalone: true}">
    <option *ngFor="let item of datalist"  [ngValue]="item">{{item.ssid}}</option>
  </select>
</div>
<div>
  <input type="text" formControlName="ssid">
</div>
<div [hidden]="wifiSelected.auth === 'WIFI_AUTH_OPEN' || !wifiSelected.auth">
  <input type="password" formControlName="psk">
</div>
<div><button class="button" type="submit">connect</button></div>
</form>
<div>
  {{wifiSelected | json}}
</div>

关键修复点说明

  • 移除混合绑定:Reactive Forms推荐统一使用formControlName,避免与ngModel混用,减少冲突;
  • 修正事件绑定:将<select>的(select)改为(change),确保选项变更时触发selected方法;
  • 配置独立控件:<select>的wifiSelected不属于FormGroup,添加[ngModelOptions]="{standalone: true}"告诉Angular不要将其关联到表单组;
  • 完善隐藏逻辑:增加!wifiSelected.auth判断,避免初始空对象导致的显示异常。

内容的提问来源于stack exchange,提问作者steeve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:20:41