[Fixed] How to display the summary of error message on top of the form in angular reactive forms

Issue

i have Validation summary component as below:

The below component fetches the ngform but unable to subscribe to statuschanges/Valuechanges and display the summary of error message.

export class ValidationSummaryComponent implements OnInit {
  @Input() form: NgForm;
  errors: string[] = [];

 constructor() { }

ngOnInit() {
  if (this.form instanceof NgForm === false) {
  throw new Error('You must supply the validation summary with an NgForm.');
}
this.form.statusChanges.subscribe(status => {
  this.resetErrorMessages();
  this.generateErrorMessages(this.form.control);
});
}

 resetErrorMessages() {
this.errors.length = 0;
}

generateErrorMessages(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(controlName => {
  const control = formGroup.controls[controlName];
  console.log('control.......... ', control);
  const errors = control.errors;
  console.log('control.errors.......... ', control.errors);

  if (errors === null || errors.count === 0) {
    return;
  }
  // Handle the 'required' case
  if (errors.required) {
    this.errors.push(`${controlName} is required`);
  }
  // Handle 'minlength' case
  if (errors.minlength) {
    this.errors.push(`${controlName} minimum length is ${errors.minlength.requiredLength}.`);
  }
  // Handle custom messages.
  if (errors.message) {
    this.errors.push(`${controlName} ${errors.message}`);
  }
});

}
}

and validation-summary.component.html

<div *ngIf="errors?.length > 0" class="validation-summary">
    <p>Please fix the following errors:</p>
<ul>
  <li *ngFor="let error of errors">{{ error }}</li>
</ul>

dynamic-form.component.ts

constructor(public formBuilder: FormBuilder) {
}
productFormGroup: FormArray;

ngOnInit() {

this.productFormGroup = this.formBuilder.array([]);
  this.ProductList.forEach(product => {
      this.productFormGroup.push(this.formBuilder.group({
        productId: [product.productId],
        displayName: [product.displayName],
        productName: [product.productName, Validators.required]
      }));
    });

}
}

dynamic-form.component.html that uses the validation summary.

    <div id="mainWrapper">
      <app-validation-summary-component [form]="userForm"></app-validation-summary-component> 
    <form #userForm="ngForm">
<div [formGroup]="product" *ngFor="let product of 
         productFormGroup.controls>
      <label>{{product.get('displayName').value}}</label>
         <input  class="form-control" 
       name="product.get('displayName').value" 
        formControlName="productName" required/>
 </div>
      <button class="btn btn-primary" type="submit" 
              [disabled]="!productFormGroup.valid">Submit </button>
       <button class="btn btn-primary" style="margin-left: 30px" type="reset" 
       (click)="reset()"> Reset </button>
       </form>
</div>

Need to display the summary of error messages on top of the dynamic form component displaying the list of label names that is blank/Invalid.

Solution

The way you are looping the formarray formgroup control is not proper inside validation-summary.component. Created stackblitz explains the solution.

https://stackblitz.com/edit/angular-mr49zh

Leave a Reply

(*) Required, Your email will not be published