表单组表单错误为空角度响应式表单

  • 本文关键字:表单 响应 错误 angular
  • 更新时间 :
  • 英文 :


当使用反应式表单时,包含无效(无效表单(的表单控件的表单组显示为无效,这是正常的,但它不包含任何错误。

我应该能够从表单组中的表单中获取所有错误,但它是空

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

检查错误:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from "@angular/forms";
import { DB1 } from 'src/app/interfaces/IDB';
import { DBS } from 'src/app/consts';
@Component({
selector: 'app-new-dashboard',
templateUrl: './new-dashboard.component.html',
styleUrls: ['./new-dashboard.component.scss']
})
export class NewDashboardComponent implements OnInit {
dbs: string[] = ["DB1", "DB2"]
selectAxisOptions:string[]  = []
newDashboardForm = new FormGroup({
name: new FormControl(null, [Validators.required]),
db: new FormControl(null, [Validators.required]),
axis: new FormControl({ value: null, disabled: true }, [Validators.required])
})
constructor() { }
ngOnInit() {
}
resetForm() {
this.newDashboardForm.reset()
}
onSelectionChanged(evt) {
let value = evt.target.value;
this.axis.enable();
switch (value) {
case 'DB1':
{
this.selectAxisOptions = [...DBS.get("DB1").values()]
break;
}
case 'DB2':
{
this.selectAxisOptions = [...DBS.get("DB2").values()]
break;
}
}
}
onSubmit() {
console.log(this.newDashboardForm);

}
get name() {
return this.newDashboardForm.get('name')
}
get db() {
return this.newDashboardForm.get('db')
}
get axis() {
return this.newDashboardForm.get('axis')
}
}

.html:

<div class="modal-body">
<form [formGroup]="newDashboardForm" (ngSubmit)="onSubmit()">
<input formControlName="name" type="text" class="form-control" placeholder="Dashboard Name">
<select formControlName="db" (change)="onSelectionChanged($event)" class="custom-select">
<option disabled="true" [selected]="true">select DB</option>
<option *ngFor="let db of dbs">{{db}}</option>
</select>
<select formControlName="axis" class="custom-select">
<option disabled="true" [selected]="true">select column</option>
<option *ngFor="let column of selectAxisOptions">{{column}}</option>
</select>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Create Dashboard</button>
</div>
</form>
</div>

您在单个表单控件上具有验证程序,而不是在整个表单组上具有验证程序。然后,您仅在无效字段上出现错误。您可以循环每个控件并像这样获取每个表单控件错误

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);
});
}

你可以在这里查看堆栈闪电战 堆栈闪电战

将初始值从 "(空字符串(更改为 null。

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

我最近遇到了类似的问题。FormGroup 跟踪整个表单是否有效的状态,但不显示特定错误。

这些错误特定于每个控制器,要查看每个错误,您必须遍历每个控制器。

我看到的一个好方法是为每个控制器准备Property

get name() { return this.newDashboardForm.get('name') }
get db() { return this.newDashboardForm.get('db') }
...

这将使您能够将控制器用作组件和模板中的普通变量。

现在查看控制器使用中的每个错误消息。

this.name?.errors

要查看模板上的错误,您可以将其用作

{{ name?.errors | json}}

最新更新