【问题标题】:How to add form validation from a list of items in Angular如何从 Angular 中的项目列表中添加表单验证
【发布时间】:2020-09-21 21:12:55
【问题描述】:

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

这里是显示的表单中的项目。您可以看到它只是一个名为“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, Validators.required],
  experience: [null, Validators.required],
  practicedStyles: [null, this.selectedPracticingStyles.length > 0]
});

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript html angular typescript angular2-form-validation


    【解决方案1】:

    您的函数 togglePracticeClass 必须更改您的 FormControl practicedStyles。您必须使用setValue。此外,如果长度> 0,您可以给这个值而不是给你的变量this.selectedPracticingStyles,否则给作为值null。所以你可以使用Validators.required

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-06
      • 2017-02-21
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多