20

When using Reactive Forms, a formGroup containing FormControls which are invalid(invalid form) is shown as invalid which is normal, but it does not contain any errors.

I should be able to get all the errors from the form in the formGroup.errors but it is null

However, The form state is invalid and under every invalid formControl it gives me the validation error What am I missing ?

check for errors:

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>
7
  • Is the first list missing this keyword in the first line of the code (so instead of newDashboardForm shouldn't it be this.newDashboardForm)? Commented Dec 14, 2019 at 23:13
  • no, it is in the initialization of the class Commented Dec 14, 2019 at 23:14
  • 8
    invalid is also true when child elements are validated and invalid, but for every group, even the form, the errors property only contains errors for that control itself. In other words: You only see errors in the form control if you added a validation to the form itself. Currently you only added validation errors to every child control. So you have to read the errors from every control. Commented Dec 14, 2019 at 23:16
  • got you, how do I add the functionality of seeing the invalid fields in the errors of the formGroup ? Commented Dec 14, 2019 at 23:17
  • 1
    Or for all fields: form.controls.forEach(c => c.errors) Commented Dec 14, 2019 at 23:25

4 Answers 4

11

You have validators on single form control, not on the whole form group. Then you have errors only on the invalid field. You can loop every control and get every single form control error like that

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

You can check the stackblitz here StackBlitz

Sign up to request clarification or add additional context in comments.

Comments

1

Change initial value from "" (empty string) to null.

Comments

1

Do your validation initializations inside the ngOnInit() method.

Comments

0

I have faced similar issue lately. The FormGroup track the states wether the overall form is valid or not, but don't show specific errors.

The errors are specific for each controller, and to see each error you must go through each controllers.

A good approach i saw is to prepare Property for each controller

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

This will enable you to use the controller as normal variable inside the component and also the template.

Now to see each the error message in the controller use.

this.name?.errors

To view the errors on the template you can use it as

{{ name?.errors | json}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.