[英]How to add form validation from a list of items in 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>
我在 the.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] });
任何帮助,将不胜感激。
您的 function togglePracticeClass 必须更改您的 FormControl practicedStyles
。 您必须使用setValue 。 此外,不是给你的变量this.selectedPracticingStyles
作为值,如果长度>0,你可以给这个值,否则给值 null。所以你可以使用Validators.required
togglePracticeClass(style: number) {
...
this.infoForm.get('practicedStyles').setValue(
this.selectedPracticingStyles.length>0? this.selectedPracticingStyles:null)
}
}
是的,一个FormControl可以存储一个数组或者null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.