简体   繁体   中英

How to add form validation from a list of items in Angular

I have a reactive form with validation and I'm trying to figure out how to add an additional check to a list of items. ex. I want at least one item to be checked for the form to be valid in addition to the other required fields.

Here are the items in the form being displayed. You can see it's just a list of items from an array called 'practicingStyles' and they are being displayed as buttons

ex.

 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>

My form in the.ts looks like this and I thought if I just added another field 'practicedStyles' and added a check '[null, this.selectedPracticingStyles.length > 0]' then that would validate it, but it doesn't work.

 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] });

Any help would be appreciated.

Your function togglePracticeClass must change your FormControl practicedStyles . You must use setValue . Futhermore, in stead of give as value your variable this.selectedPracticingStyles , you can give this value if length>0, else give as value null. So you can use Validators.required

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

Yes, a FormControl can store an array or null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM