如何从Angular中的项目列表中添加表单验证

问题描述

我有一个带有验证的反应式表单,我试图弄清楚如何向项目列表中添加其他检查。例如除了其他必填字段之外,我还希望至少检查一项以确保该表单有效。

以下是正在显示的表单中的项目。您可以看到它只是来自名为“ practicingStyles”的数组中的项的列表,它们正显示为按钮

例如。

 selectedPracticingStyles: number[] = [];

togglePracticeClass(style: number) {
  if (!this.selectedPracticingStyles.includes(style)) {
    this.selectedPracticingStyles.push(style);
  } else {
    this.selectedPracticingStyles.splice(this.selectedPracticingStyles.indexOf(style),1);
  }
}
<div class="form-group">
  <label class="control-label">Practicing Styles:</label>
  <div class="btn-toolbar special">
    <ng-container *ngFor="let practiceStyle of practicingStyles; let i = index">
      <button type="button" class="btn mb-2" (click)="togglePracticeClass(practiceStyle.id)">
{{practiceStyle.name}}
     </button>
    </ng-container>
  </div>
</div>

.ts中的表单看起来像这样,我想如果我只是添加一个字段“ practicedStyles”并添加检查“ [null,this.selectedPracticingStyles.length> 0]”,那将对其进行验证,但它不会不行。

this.infoForm = this.fb.group({
  gender: [null,Validators.required],introduction: [null],yearStarted: [null,experience: [null,practicedStyles: [null,this.selectedPracticingStyles.length > 0]
});

任何帮助将不胜感激。

解决方法

您的功能togglePracticeClass必须更改您的FormControl practicedStyles。您必须使用setValue。此外,如果length> 0,则可以给定该值,而不是变量this.selectedPracticingStyles,否则给null。因此,您可以使用Validators.required

togglePracticeClass(style: number) {
  ...
  this.infoForm.get('practicedStyles').setValue(
        this.selectedPracticingStyles.length>0? this.selectedPracticingStyles:null)
  }
}

是的,FormControl可以存储数组或null