Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: FormGroup: How to display custom error message

Tags:

forms

angular

Im building a frontend using Angular4. If a user submits a faulty form, an error message should be displayed.

At the moment, my error handling looks like this:

// This code is run when a response from the server is received
if ('error' in server_response) {
    for (let key in server_response.error {
      this.form.controls[key].setErrors({'error': true});
      let error_message_from_server = server_response.error[key];
    }
}

How I display the error in HTML:

<span class="error" *ngIf="field.invalid">Error: {{field.errors.error}} <br></span>

At the moment the field.invalid becomes true when a error is received, but the field.errors.error in an empty string.

Question: How can I set the field.errors.error message? This message should be the string in error_message_from_server

Please note that solving this by the use of if-statements in the HTML code is not an option. The amount of potential errors are in the hundreds.

like image 412
Vingtoft Avatar asked Aug 10 '17 13:08

Vingtoft


2 Answers

this.form.controls[key].setErrors({'error': true}); // key is error and value is boolean not a string

try to set a string type value

for (let key in server_response.error {
  this.form.controls[key].setErrors({'error': erver_response.error[key]});
//Calling `setErrors` will also update the validity of the parent control.
}
like image 176
Jorawar Singh Avatar answered Oct 22 '22 16:10

Jorawar Singh


For the error string to be available on html level, you have to declare it on your component level:

error_message_from_server: string;

Then, on your response from server, you set the message to that string:

// This code is run when a response from the server is received
if ('error' in server_response) {
    for (let key in server_response.error {
      this.form.controls[key].setErrors({'error': true});
      error_message_from_server = server_response.error[key];
    }
}

Then you bind the string into your element:

<span class="error" *ngIf="field.invalid">Error: {{error_message_from_server}} <br></span>

like image 2
BogdanC Avatar answered Oct 22 '22 16:10

BogdanC