首页 > 解决方案 > 复选框类型中的角度错误验证

问题描述

我有一个包含某些类型输入的表单。类型中的验证有错误checkbox。请参阅stackblitz演示。

首先,检查第一项。然后选中第二个,然后取消选中第一个。它显示错误信息

html:

<form name="form" (ngSubmit)="addBookletForm.valid && addBooklet()" #addBookletForm="ngForm" novalidate >
  <label *ngFor="let option of levelCheckboxes">
    <div *ngIf="( booklet_level.touched || addBookletForm.submitted) && booklet_level.invalid && booklet_level.errors.required">
        <div class="saz-alert saz-alert-red saz-alert-small saz-color-red" *ngIf="booklet_level.errors.required">
          This is required!
        </div>
    </div>
    <input name="booklet_level" #booklet_level="ngModel" required value="{{option.value}}" [(ngModel)]="option.checked" type="checkbox">
    {{option.name}}

  </label>
</form>

打字稿:

levelCheckboxes = [
    { name:'one', value:'1', checked:false },
    { name:'two', value:'2', checked:false },
    { name:'three', value:'3', checked:false }
]

标签: angularangular-forms

解决方案


问题是您在每个复选框输入上使用相同的 name 属性值,booklet_level. 因为您使用的是ngForm所有NgModels合并为一个。所以,你会得到非常奇怪和意想不到的行为。

如果您将名称更改为这样的名称,它将起作用:

<input name="booklet_level_{{option.name}}" required 
       type="checkbox" value="{{option.value}}" 
       [(ngModel)]="option.checked" #booklet_level="ngModel">

推荐阅读