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.
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.
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With