表单验证错误消息未以 Angular 8 的反应形式显示 [英] Form Validation Error Message Not Showing in reactive forms in angular 8

查看:35
本文介绍了表单验证错误消息未以 Angular 8 的反应形式显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不显示此表单控件错误消息我有一个数组,我正在阅读它并生成动态问题.我找不到我在这段代码中犯了什么错误.

我必须显示 4 条错误信息

  1. 必填
  2. 最小值验证
  3. 最大值验证
  4. 唯一值验证

我有一个包含问题的数组

questions: any = [{编号:13,调查编号:5,qNo: 3,问题:请按重要性对以下特征进行排序,其中 1 对您来说最重要.?",qType: 3,没有答案:4,答案类型:1,答案:['位置'、'舒适'、'服务'、'物有所值']}];

我同样动态生成了表单控制器,

createForms(): 任何 {this.surveyQuestionForm = this.fb.group(this.questions.reduce((group: any, question: { qNo: string; }) => {return Object.assign(group, { ['q' + question.qNo]: this.buildSubGroup(question) });}, {}));}私人 buildSubGroup(问题){开关(问题.qType){案例3:返回 this.fb.group(question.answers.reduce((subGroup, answer) => {返回 Object.assign(subGroup, { [answer]: ['', [Validators.required, Validators.min(1), Validators.max(3)]] });}, {}), { 验证器:[this.uniqueNumbersValidator()] });默认:throw new Error('未处理的问题类型');}}uniqueNumbersValidator() {return (ctrl: AbstractControl) =>{const fg = ctrl as FormGroup;让 allUnique = true;常量值 = [];Object.values(fg.controls).forEach(fc => {const val = fc.value;如果 (val && allUnique) {if (values.includes(val) && allUnique) {allUnique = 假;}values.push(val);}});返回(allUnique)?null : { notAllUnique: true };};}

这是我的html代码

<label class="control-label">{{question.qNo}}){{question.question}}</label><div class="ml-3"><表格><tr *ngFor="let anwr of question.answers; let a=index"><td>{{a+1}}.{{anwr}} </td><div class="无效反馈"*ngIf="surveyQuestionForm.get('q'+ question.qNo).touched&&SurveyQuestionForm.get('q'+ question.qNo).hasError('required')">需要回答

<div class="无效反馈"*ngIf="surveyQuestionForm.get('q'+ question.qNo).touched&&SurveyQuestionForm.get('q'+ question.qNo).hasError('max')">最大值

<div class="无效反馈"*ngIf="surveyQuestionForm.get('q'+ question.qNo).touched&&SurveyQuestionForm.get('q'+ question.qNo).hasError('min')">最小值

<div class="无效反馈"*ngIf="surveyQuestionForm.get('q'+ question.qNo).touched&&SurveyQuestionForm.get('q'+ question.qNo).hasError('notAllUnique')">已插入值

<td><input type="number" style="width:40px;"id="q{{question.qNo}}_{{a}}"[ngClass]="{'is-invalid':surveyQuestionForm.get('q'+ question.qNo).errors&&SurveyQuestionForm.get('q'+ question.qNo).touched}" formControlName="{{anwr}}" class="text-center"/></td></tr>

这是stackblitz代码https://stackblitz.com/edit/angular-pxdesk

请告诉我这是什么问题.

谢谢

解决方案

这里的问题是你没有区分有错误的组或有错误的控件.

您需要确保在验证器不在控件上时访问控件上的错误,而在组上时访问组上的错误,因此您需要这样做:

需要回答

<div class="无效反馈"*ngIf="surveyQuestionForm.get('q'+ question.qNo).get(anwr).touched &&surveyQuestionForm.get('q'+ question.qNo).get(anwr).hasError('max')">最大值

<div class="无效反馈"*ngIf="surveyQuestionForm.get('q'+ question.qNo).get(anwr).touched &&surveyQuestionForm.get('q'+ question.qNo).get(anwr).hasError('min')">最小值

用于控制级错误.如果你不确保检查控件是否也被触摸过,那么错误就会出现在错误的时间.

对于组级错误,您可能希望将其移到单个控件之外,并与组一起显示,因为它是组级错误.在您当前的方案中,如果您有重复的值,错误将出现在每个触摸控件旁边.所以改为这样做...

已插入值

在你的 ngFor 之外的答案.请注意,我们正在访问该组,因为这是一个组级错误.

旁注:您可能希望最大验证器为 4 而不是 3,因为您需要 4 个不同的数字.

这是固定的闪电战:https://stackblitz.com/edit/angular-hbtvnc?file=src/app/app.component.html

Why is this form control error messages not showing I have an array and I'm reading it and generate dynamically questions. I can't find what is the mistake I have done in this code.

I have to show 4 error messages

  1. Required
  2. Min value validate
  3. Max value validate
  4. Unique value validate

I have an array which contains a question

questions: any = [{
      id: 13,
      surveyNo: 5,
      qNo: 3,
      question: 'Please rank the following features in order of importance,where 1 is the most important to you.?',
      qType: 3,
      noAnswrs: 4,
      answerType: 1,
      answers: ['Location', 'Confort', 'Service', 'Value for money']
    }];

I generated form controller dynamically likewise,

createForms(): any {
    this.surveyQuestionForm = this.fb.group(
      this.questions.reduce((group: any, question: { qNo: string; }) => {
        return Object.assign(group, { ['q' + question.qNo]: this.buildSubGroup(question) });
      }, {})
    );
  }

private buildSubGroup(question) {
    switch (question.qType) {
       case 3:
        return this.fb.group(
          question.answers.reduce((subGroup, answer) => {
            return Object.assign(subGroup, { [answer]: ['', [Validators.required, Validators.min(1), Validators.max(3)]] });
          }, {}), { validators: [this.uniqueNumbersValidator()] }
        );
        default:
        throw new Error('unhandled question type');
    }
  }

uniqueNumbersValidator() {
    return (ctrl: AbstractControl) => {
      const fg = ctrl as FormGroup;
      let allUnique = true;
      const values = [];
      Object.values(fg.controls).forEach(fc => {
        const val = fc.value;
        if (val && allUnique) {
          if (values.includes(val) && allUnique) {
            allUnique = false;
          }
          values.push(val);
        }
      });
      return (allUnique) ? null : { notAllUnique: true };
    };
  }

Here is my html code

<div class="form-group" formGroupName="{{'q' + question.qNo}}">
    <label class="control-label"> {{question.qNo}})
        {{question.question}}</label>
    <div class="ml-3">
        <table>
            <tr *ngFor="let anwr of question.answers; let a=index">
                <td>{{a+1}}. {{anwr}} </td>
                <div class="invalid-feedback"
                    *ngIf="surveyQuestionForm.get('q'+ question.qNo).touched 
                           && surveyQuestionForm.get('q'+ question.qNo).hasError('required')">
                    Answer required</div>
                <div class="invalid-feedback"
                    *ngIf="surveyQuestionForm.get('q'+ question.qNo).touched 
                           && surveyQuestionForm.get('q'+ question.qNo).hasError('max')">
                    max value</div>
                <div class="invalid-feedback"
                    *ngIf="surveyQuestionForm.get('q'+ question.qNo).touched 
                           && surveyQuestionForm.get('q'+ question.qNo).hasError('min')">
                    min value</div>
                <div class="invalid-feedback"
                    *ngIf="surveyQuestionForm.get('q'+ question.qNo).touched 
                           && surveyQuestionForm.get('q'+ question.qNo).hasError('notAllUnique')">
                    Already inserted value</div>
                <td>
                    <input type="number" style="width:40px;" id="q{{question.qNo}}_{{a}}"
                        [ngClass]="{'is-invalid': surveyQuestionForm.get('q'+ question.qNo).errors 
                                   && surveyQuestionForm.get('q'+ question.qNo).touched}" formControlName="{{anwr}}" class="text-center" />
                </td>
            </tr>

        </table>
    </div>
</div>

Here is stackblitz code https://stackblitz.com/edit/angular-pxdesk

please tell me what is the problem having this.

thanks

解决方案

the problem here is you're not differentiating between the group having an error or the control having an error.

you need to make sure you're accessing the error on the control when the validator is o the control, and on the group when it's on the group, so you need to be doing this:

<div class="invalid-feedback"
    *ngIf="surveyQuestionForm.get('q'+ question.qNo).get(anwr).touched && surveyQuestionForm.get('q'+ question.qNo).get(anwr).hasError('required')">
    Answer required</div>
<div class="invalid-feedback"
    *ngIf="surveyQuestionForm.get('q'+ question.qNo).get(anwr).touched && surveyQuestionForm.get('q'+ question.qNo).get(anwr).hasError('max')">
    max value</div>
<div class="invalid-feedback"
    *ngIf="surveyQuestionForm.get('q'+ question.qNo).get(anwr).touched && surveyQuestionForm.get('q'+ question.qNo).get(anwr).hasError('min')">
    min value</div>

for the control level errors. If you don't make sure to be checking if the control has been touched as well, then the errors will appear at the wrong time.

for the group level error, you probably want to move it outside of the individual controls, and display it with the group, since it is a group level error. In your current scheme, if you had a duplicate value, the error would appear next to every touched control. so do this instead...

<div class="invalid-feedback"
        *ngIf="surveyQuestionForm.get('q'+ question.qNo).touched && surveyQuestionForm.get('q'+ question.qNo).hasError('notAllUnique')">
        Already inserted value</div>

outside of your ngFor over the answers. notice here, we're accessing the group since this is a group level error.

side note: you probably want your max validator to be 4 and not 3, since you want 4 different numbers.

here is the fixed blitz: https://stackblitz.com/edit/angular-hbtvnc?file=src/app/app.component.html

这篇关于表单验证错误消息未以 Angular 8 的反应形式显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆