Angular FormGroup form errors为空

Angular FormGroup form errors为空,angular,Angular,使用被动表单时,包含无效(无效表单)的FormControl的formGroup显示为正常的无效,但不包含任何错误 我应该能够从formGroup.errors中的表单中获取所有错误,但它为空 但是,表单状态无效,在每个无效的formControl下,它都会给我验证错误 我错过了什么 检查错误: 从'@angular/core'导入{Component,OnInit}; 从“@angular/forms”导入{FormGroup、FormControl、Validators}; 从'src/ap

使用被动表单时,包含无效(无效表单)的FormControl的formGroup显示为正常的无效,但不包含任何错误

我应该能够从formGroup.errors中的表单中获取所有错误,但它为空

但是,表单状态无效,在每个无效的formControl下,它都会给我验证错误 我错过了什么

检查错误:

从'@angular/core'导入{Component,OnInit};
从“@angular/forms”导入{FormGroup、FormControl、Validators};
从'src/app/interfaces/IDB'导入{DB1};
从'src/app/consts'导入{DBS};
@组成部分({
选择器:“应用程序新建仪表板”,
templateUrl:'./new dashboard.component.html',
样式URL:['./new dashboard.component.scss']
})
导出类NewDashboardComponent实现OnInit{
dbs:string[]=[“DB1”,“DB2”]
选择轴选项:字符串[]=[]
newDashboardForm=新表单组({
名称:new FormControl(null,[Validators.required]),
db:new FormControl(null,[Validators.required]),
axis:newformcontrol({value:null,disabled:true},[Validators.required])
})
构造函数(){}
恩戈尼尼特(){
}
重置表单(){
this.newDashboardForm.reset()
}
onSelectionChanged(evt){
让值=evt.target.value;
这个.axis.enable();
开关(值){
案例“DB1”:
{
this.selectAxisOptions=[…DBS.get(“DB1”).values()]
打破
}
案例‘DB2’:
{
this.selectAxisOptions=[…DBS.get(“DB2”).values()]
打破
}
}
}
onSubmit(){
console.log(this.newDashboardForm);
}
获取名称(){
返回此.newDashboardForm.get('name')
}
get db(){
返回此.newDashboardForm.get('db'))
}
获取轴(){
返回此.newDashboardForm.get('axis'))
}
}
html:


选择数据库
{{db}}
选择列
{{column}}
创建仪表板

将初始值从“”(空字符串)更改为null。

ngOnInit()
方法中进行验证初始化

您在单个表单控件上有验证器,而不是在整个表单组上。那么,只有无效字段有错误。您可以循环每个控件并获得每个表单控件错误,就像这样

  onSubmit() {
    // Get all Form Controls keys and loop them
    Object.keys(this.newDashboardForm.controls).forEach(key => {
      // Get errors of every form control
      console.log(this.newDashboardForm.get(key).errors);
    });
  }

您可以在这里检查stackblitz

是否是代码第一行中缺少的第一个列表
this
关键字(因此不是
newDashboardForm
应该是
this.newDashboardForm
)?否,它在类的初始化中
无效
在子元素被验证和无效时也是正确的,但是对于每个组,甚至是表单,
errors
属性只包含该控件本身的错误。换句话说:只有在表单本身添加验证时,才能在表单控件中看到错误。当前,您只向每个子控件添加了验证错误。因此,您必须读取每个控件的错误。明白了,我如何添加查看formGroup错误中无效字段的功能?或者对于所有字段:
form.controls.forEach(c=>c.errors)