Angular 8/9复选框验证-最多选择3个复选框

问题描述 投票:0回答:1

我如何在此处添加验证,最多只能选择3个复选框。我已经添加了必填验证,以确保至少选中了1个复选框因此,选择的最小复选框为1,选择的最大复选框为3。我的.ts代码是

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  form: FormGroup;
  Data: Array<any> = [
    { name: 'Pear', value: 'pear' },
    { name: 'Plum', value: 'plum' },
    { name: 'Kiwi', value: 'kiwi' },
    { name: 'Apple', value: 'apple' },
    { name: 'Lime', value: 'lime' }
  ];

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      checkArray: this.fb.array([], [Validators.required])
    })
  }

  onCheckboxChange(e) {
    const checkArray: FormArray = this.form.get('checkArray') as FormArray;

    if (e.target.checked) {
      checkArray.push(new FormControl(e.target.value));
    } else {
      let i: number = 0;
      checkArray.controls.forEach((item: FormControl) => {
        if (item.value == e.target.value) {
          checkArray.removeAt(i);
          return;
        }
        i++;
      });
    }
  }

  submitForm() {
    console.log(this.form.value)
  }
}

我的html文件是

<form [formGroup]="form" (ngSubmit)="submitForm()" novalidate>

  <div *ngFor="let data of Data; let i=index">
    <label>
      <input type="checkbox" [value]="data.value" (change)="onCheckboxChange($event)" />
      {{data.name}}
    </label>
  </div>

  <p class="error" *ngIf="this.form.controls['checkArray'].errors?.required">
    Checkbox is required, select atleast one value.
  </p>

  <input type="submit" value="Submit">
</form>
angular typescript angular7
1个回答
0
投票

您可以在用户单击第四个复选框时取消选中。

if (e.target.checked) {
  // Determining whether 3 checkobx are checked or not
  if (checkArray.length <= 3) {
    checkArray.push(new FormControl(e.target.value));
  } else {
     // Resetting the checkbox to original state
     e.terget.checked = !e.terget.checked;
  }

} 
© www.soinside.com 2019 - 2024. All rights reserved.