angular - 如何使用反应式表单模块验证三个复选框?
问题描述
这应该相对容易,不知道为什么我在挣扎。
我有三个复选框,我想确保用户只点击一个。所以验证器应该检查其他两个框是否已被选中,并防止再次选择。它应该确保至少检查一个。
我尝试过使用自定义验证器,但您只能传递一个控件。我需要一些可以检查所有框以进行验证的东西。
<form class="example-section" [formGroup]="queryType">
<mat-checkbox class="example-margin" [(ngModel)]="artist" formControlName="artist">Artist</mat-checkbox>
<mat-checkbox class="example-margin" [(ngModel)]="album" formControlName="album">Album</mat-checkbox>
<mat-checkbox class="example-margin" [(ngModel)]="track" formControlName="track">Track</mat-checkbox>
</form>```
export class SearchComponent implements OnInit, OnChanges {
filteredSearchItems: Observable<SearchResult[]>;
isLoading = false;
searchForm: FormGroup;
queryType: FormGroup;
disabled: boolean = false;
artist: boolean;
album: boolean;
track: boolean;
constructor(private searchService: SearchService, private fb:
FormBuilder) {
this.searchForm = this.fb.group({
searchInput: new FormControl(null)
});
this.queryType = this.fb.group({
'artist': new FormControl(false,[CustomValidators.validateQuery]),
'album': new FormControl(false,[CustomValidators.validateQuery]),
'track': new FormControl(false,[CustomValidators.validateQuery])
});
}
export class CustomValidators {
static validateQuery(control: FormGroup): { [s: string]: boolean }
{//not sure how to pass in all boxes
for(const con of control.controls) { // somewhere here is the answer
if(con.value) {
return { alreadyChecked: true}
}
}
return null;
};
}
解决方案
有两种可能的解决方案。
1.)您可以使用单选按钮而不是复选框,这样您只能选择这三个选项中的一个。
2.) 如果你真的想使用复选框。你可以像这样实现它。还创建了一个Stackblitz Demo供您参考
<mat-checkbox class="example-margin"
formControlName="artist"
[disabled]="album || track">Artist</mat-checkbox> // This will be disabled when album or track is already checked
<mat-checkbox class="example-margin"
formControlName="album"
[disabled]="artist || track">Album</mat-checkbox> // This will be disabled when artist or track is already checked
<mat-checkbox class="example-margin"
formControlName="track"
[disabled]="artist || album">Track</mat-checkbox> // This will be disabled when artist or album is already checked.
这样,用户只能从这 3 个选项中检查一项。
笔记:
- 您应该决定是使用模板驱动表单 [(ngModel)] 还是反应式表单模块 (formControlName),因为您无法在输入标签中合并这两者。
推荐阅读
- c# - 无法在 for 循环中打印随机切换案例字符串
- python-3.x - csv仅在python中写入最后一行
- javascript - 数据层变量不起作用 - GTM 上的自定义 HTML 代码
- python - 加载使用 FloPy MODFLOW 创建的 MNW2 包时出错
- node.js - 使 VSCode 扩展解析实时文档并访问输出
- actionscript-2 - 测试 AS2 消息的客户端
- c# - 如何优化将指针数组复制到另一个数组?
- node.js - Nginx proxy_reverse 和节点服务器。您在哪里看到来自上游 NODE 服务器的控制台日志 OUTPUT?
- math - 在不同计数算法的公式中,^ 符号是什么意思?
- c# - Blazor 在布局上加载元素