【问题标题】:Reactive Form Validators.Required not functioning on formControlsReactive Form Validators.Required 在 formControls 上不起作用
【发布时间】:2018-02-05 01:56:05
【问题描述】:

这是我在 app.component.html 中循环的模拟数据数组

questions: [
{question: 'Question-1'},
{question: 'Question-2'},
{{question: 'Question-3'}
]

在我的 app.component.ts 中,如下所示,由于我使用的是响应式表单方法,我已经实例化了表单组并声明了一个名为“note”的 formControl,它是按要求声明的:

导出类示例 {

regPresentationForm: FormGroup;

this.regPresentationForm = new FormGroup ({
   note: new FormControl(null, Validators.required),
});

}

在我的 HTML 组件中,我循环遍历数组并显示文本字段,因此将有三个文本框,每个文本框都有 note 作为我的 formControl

<ng-container *ngFor = "let question of questions">
  <textarea type="text" id="textArea" placeholder="Enter the Note" class="form-control" formControlName = "note">
  </textarea>
</ng-container>

由于需要注释表单控件,因此我将禁用提交按钮,如下所示:

<button class="btn btn-primary" type="submit"[disabled] =  "!regPresentationForm.valid">
  Save & Continue
</button>

问题:

问题是,如果我在第一个文本框中输入文本,表单会变得有效,因此 Angular 将其视为重复三次的单个框,这不应该发生,它应该单独考虑每个注释字段(注释 formcontrol 的 3 个实例,因为迭代完成三次)

不知道如何解决这个需要帮助。

我希望我很清楚。

【问题讨论】:

    标签: angular5 angular-reactive-forms


    【解决方案1】:

    您可以像这样循环 formControl: 在 ts 方面:

     form2: FormGroup;
     testData:any;
     formDataInfo: any;
    
    
      constructor() {  }
    
     ngOnInit() {
        this.testData = [];
        this.formDataInfo = {}; 
    
       for(var i=0; i<2; i++){
        var currentNote = 'note' + i;
    
        this.formDataInfo[currentNote] = new FormControl(null, 
        Validators.required);
    
        this.testData.push({ "value": currentNote, "key": "firstName1", 
          "label": "First name",
          "required": true, "order": 1, "controlType": "textbox", 
          "type": "text" 
        }); 
    
      }
      this.form2 = new FormGroup (
        this.formDataInfo
      );
    }
    

    在 HTML 方面:

    <div [formGroup]="form2">
      <ng-container *ngFor="let question of testData" class="form-row">
        {{question | json}} {{question.key}}
            <textarea type="text" placeholder="Enter the Note"    
              class="form-control" [formControlName]="question.value" 
              [required]="question.required"> 
            </textarea> 
        </ng-container>
    </div>
    

    【讨论】:

    • 需要在ts端使用问题循环表单控件
    • 正好在 ts 端我也需要循环。当你在 ts 端回答时,你正在手动添加注释 formControls,我需要根据数组动态执行它。我会循环在 ts 端的问题数组上也是为了在每次迭代中拥有尽可能多的表单控件
    • 是的。我猜这是唯一可能的解决方案
    • 但问题是我正在尝试并且在 ts 方面我无法按照您在 html 上使用 note{{$index} 的建议动态添加 formControl 键。我正在以这种方式尝试 ts 方面:notes${this.i} 其中 i 是循环迭代器索引。但是 formGroup 键不能取这个表达式。仍然不知道如何实现解决方案。
    • 我编辑了我的答案。你可以关注这个。如果仍有错误,请告诉我。
    猜你喜欢
    • 2023-03-07
    • 2021-06-04
    • 2021-05-02
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多