gpt4 book ai didi

angular - FormGroup 表单错误为 null Angular Reactive Forms

转载 作者:行者123 更新时间:2023-12-02 04:21:45 26 4
gpt4 key购买 nike

使用 Reactive Forms 时,包含无效的 FormControl(无效表单)的 formGroup 显示为无效,这是正常的,但不包含任何错误。

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

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

检查错误:

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);
});
}
您可以在此处查看堆栈 Blitz StackBlitz

关于angular - FormGroup 表单错误为 null Angular Reactive Forms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59339882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com