Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically set global form error in Angular 2?

Tags:

angular

I have a function which appends server (remote) errors to the fields in my form. How can I add global errors to the form (i.e not just one field)? I marked it with TODO

import {NgForm} from 'angular2/common';

export function appendRemoteErrorsToForm(form: NgForm, modelState: Map<string, Array<string>>) {
  if (!modelState) {
    return;
  }
  let _globalKey = 'global';
  for (let key in modelState) {
    let errors = modelState[key];
    if (key !== 'global') {
      form.controls[key].setErrors({
        remote: errors
      });
    } else {
      //todo
    }
  }
}
like image 509
williamsandonz Avatar asked Apr 01 '26 09:04

williamsandonz


1 Answers

I would set the error on the ControlGroup associated with the NgForm directive:

for (let key in modelState) {
  let errors = modelState[key];
  if (key !== 'global') {
    form.controls[key].setErrors({
      remote: errors
    });
  } else {
    form.control.setErrors({ // <-----
      remote: errors
    });
  }
}

This way you will be able to reference it this way:

<form #companyForm="ngForm">
  <div *ngIf="companyForm.control.errors">
    Display errors
  </div>
</form>
like image 61
Thierry Templier Avatar answered Apr 04 '26 00:04

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!