简体   繁体   English

Angular 2:FormGroup:如何显示自定义错误消息

[英]Angular 2: FormGroup: How to display custom error message

Im building a frontend using Angular4. 我正在使用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: 我如何在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. 此刻的field.invalid当收到一个错误变成正确的,但在field.errors.error一个空字符串。

Question: How can I set the field.errors.error message? 问题:如何设置field.errors.error消息? This message should be the string in error_message_from_server 此消息应该是error_message_from_server的字符串

Please note that solving this by the use of if-statements in the HTML code is not an option. 请注意,通过在HTML代码中使用if语句来解决此问题不是一种选择。 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: 要使错误字符串在html级别上可用,您必须在组件级别声明它:

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM