angular - 如何为 FormGroup 创建自定义验证器
问题描述
我有一个带有 6 个字段的 formGroup 对象。6 个字段中有 5 个是强制性的,这意味着它们中的任何一个都必须具有值才能成为有效的表单。5 个字段中的哪一个具有值并不重要,只要其中一个具有值即可。如何为表单添加自定义验证器?
解决方案
假设您使用模板驱动表单的 2 方式绑定。
@Component({
selector: 'my-component',
template: `
...
<input name="input1" [(ngModel)]="input1" [required]="!checkIfValueExists()"/>
<input name="input2" [(ngModel)]="input2" [required]="!checkIfValueExists()"/>
<input name="input3" [(ngModel)]="input3" [required]="!checkIfValueExists()"/>
`
})
export class MyComponent {
input1: string;
input2: string;
input3: string;
constructor() {}
checkIfValueExists(): boolean {
return input1 || input2 || input3;
}
}
推荐阅读
- javascript - 如果子字符串已知,则返回一个字符串
- django - 跨父表单和表单集验证表单
- c - 寻找最近的出发时间 C
- java - 使用 Java 的 ColorGame(如扫雷)
- scala - Spark Twitter API 失败
- python - 如何控制所有文件扩展名或不控制另一个目录?仅一行
- c - 在链表中搜索事件
- node.js - 如何解决 NodeJS GET/POST 请求中的错误 [ERR_HTTP_HEADERS_SENT]
- android-sqlite - Android Sqlite - 异常:请求索引 -1,大小为 32 --- 由于大尺寸?
- java - ROOM Android SQLite 数据库 - 无法创建表