Angular 5表单POST问题:提交时出现Cannot read property 'value'未定义错误
解决Angular表单的
ERROR TypeError: Cannot read property 'value' of undefined错误 这个错误我在日常开发里碰到过好多次,大概率是你的表单组或者控件还没正确初始化,就被代码尝试访问value属性了。结合你给出的HTML代码片段,我给你整理几个最可能的原因和对应的解决办法:
1. 先确保组件类里正确初始化了FormGroup和控件
首先,你得在组件的.ts文件里把表单组和name控件给创建出来,不然模板里绑定的angForm就是个undefined,后续访问肯定报错:
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ // 你的组件元数据(selector、templateUrl这些) }) export class YourComponent implements OnInit { angForm: FormGroup; ngOnInit() { // 初始化表单组,把name控件加进去,还可以按需加验证规则 this.angForm = new FormGroup({ name: new FormControl('', Validators.required) }); } }
建议在ngOnInit里初始化表单,而不是构造函数里,这是Angular的最佳实践哦。
2. 模板里访问控件前先判断表单是否存在
从你的HTML片段能看到有*ngIf="angForm.controls['name'].invalid && ...",如果angForm还没初始化完成,这行代码就会去读undefined的controls属性,直接触发错误。你可以先加个判断:
<div *ngIf="angForm && angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)"> <!-- 这里放你的错误提示内容 --> </div>
或者更优雅一点,在组件类里写个getter来获取控件:
get nameControl() { return this.angForm.get('name'); }
然后模板里就可以这么用,既简洁又能避免undefined的问题:
<div *ngIf="nameControl.invalid && (nameControl.dirty || nameControl.touched)"> <!-- 错误提示 --> </div>
3. 注意模板引用变量#name的访问时机
你在input上用了#name的模板引用变量,如果是在组件类里用@ViewChild('name')来获取这个DOM元素,一定要等到AfterViewInit钩子之后再访问它的value——因为组件初始化早期,DOM元素还没渲染好,直接读会得到undefined:
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core'; export class YourComponent implements OnInit, AfterViewInit { @ViewChild('name') nameInput: ElementRef; ngAfterViewInit() { // 在这里访问才是安全的 console.log(this.nameInput.nativeElement.value); } }
4. 别忘导入ReactiveFormsModule
最后再确认一下,你的模块(比如AppModule或者对应的功能模块)里有没有导入ReactiveFormsModule,不然Angular根本识别不了formGroup、formControlName这些指令:
import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ // 其他你需要的模块 ReactiveFormsModule ] }) export class YourModule { }
先从这几个方向排查,基本就能解决这个错误啦!
内容的提问来源于stack exchange,提问作者Pushparaj
相关产品推荐
相关产品推荐

