angular - 复选框类型中的角度错误验证
问题描述
我有一个包含某些类型输入的表单。类型中的验证有错误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 }
]
解决方案
问题是您在每个复选框输入上使用相同的 name 属性值,booklet_level
. 因为您使用的是ngForm
所有NgModels
合并为一个。所以,你会得到非常奇怪和意想不到的行为。
如果您将名称更改为这样的名称,它将起作用:
<input name="booklet_level_{{option.name}}" required
type="checkbox" value="{{option.value}}"
[(ngModel)]="option.checked" #booklet_level="ngModel">
推荐阅读
- python-3.x - 无法使用 Gstreamer-Python 为两个摄像头设置参数
- cordova - 什么是cordova ios config.xml 文件设置
- ms-access - 在 ms 中访问如何以编程方式将查询导出到文本文件
- sql-server - 如何在 SQL Server 中的字符串中查找整数值
- python-3.x - 在 Python 中随时间序列数据移动具有高斯形状的窗口
- fullpage.js - Fullpage.js - 移动设备上的锚点在滚动时不会回到该部分的顶部
- spring - 在 repo.spring.io 端点遇到间歇性问题
- javascript - 我似乎无法使“getElementsByID”正常工作,始终返回“未捕获的类型错误:无法读取未定义的属性。”
- jquery - jQuery Sortable 获取新的父 ID?
- c++ - 已创建 GitHub 存储库但无法上传 VS 解决方案