FormGroup 表单错误为 null Angular Reactive Forms

MD1*_*D10 11 angular

使用 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')
  }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

小智 9

您在单个表单控件上有验证器,而不是在整个表单组上。那么您仅在无效字段上出现错误。您可以循环每个控件并获取每个表单控件错误

  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);
    });
  }
Run Code Online (Sandbox Code Playgroud)

你可以在这里查看 stackblitz StackBlitz


小智 1

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