Angular 2: FormGroup: How to display custom error message

Viewed 14659

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.

2 Answers
Related