在Angular 6应用程序的注册表格中,我有一个复选框已被选中。我需要检查用户是否已取消选中该复选框,是否已选中,所以我想显示一条错误消息。
这是我在.html文件中的复选框,
<div class="form-group">
<div class="round">
<input
type="checkbox"
id="checkbox33"
formControlName="agree">
<label for="checkbox33"></label>
</div>
<small class="text-muted">Agree to our <a href="#" class="link">Terms
Of Use</a> and <a href="#" class="link">Privacy Policy</a>.
</small>
<span *ngIf="!worldWideRegisterForm.get('agree').valid" class="text-danger">You should agree!</span>
</div>
这是.ts文件中的ngOnInit()
ngOnInit() {
this.worldWideRegisterForm = new FormGroup({
'userName': new FormGroup({
firstName: new FormControl(null, Validators.required),
lastName: new FormControl(null, Validators.required)
}),
'email': new FormControl(null, [Validators.required, Validators.email]),
'phone': new FormControl(null, Validators.required),
'address': new FormGroup({
line1: new FormControl(null, Validators.required),
line2: new FormControl(null),
}),
'area': new FormGroup({
'province': new FormControl(null, Validators.required),
'city': new FormControl(null, Validators.required),
'postalCode': new FormControl(null, Validators.required),
}),
'password': new FormControl(null, [Validators.required, Validators.minLength(6)]),
'agree': new FormControl(true, Validators.required)
});
}
答案 0 :(得分:3)
使用角度验证器requiredTrue
'agree': new FormControl(true, Validators.requiredTrue)
错误
<div *ngIf="myTrue.hasError('required')">
Agree the T&C
</div>
答案 1 :(得分:1)
代替false
与'agree': new FormControl(true, Validators.required)
一起尝试。
答案 2 :(得分:0)
我可以通过编写复选框的自定义验证来解决我的问题,并获得确切的输出作为其他答案。我也想分享我的答案。
这是我的复选框的.html,
<div class="form-group">
<div class="round">
<input
type="checkbox"
id="checkbox33"
formControlName="agree">
<label for="checkbox33"></label>
</div>
<small class="text-muted">Agree to our <a href="#" class="link">Terms
Of Use</a> and <a href="#" class="link">Privacy Policy</a>.
</small>
<span *ngIf="!worldWideRegisterForm.get('agree').valid" class="text-danger">
<span *ngIf="worldWideRegisterForm.get('agree').errors['checkBoxIsForbidden']">Agree to our terms & conditions.</span>
</span>
</div>
这就是我添加到.ts文件中的内容
'agree': new FormControl(true, [Validators.required, this.forbiddenCheckBox])
//fuction to check the checkbox
forbiddenCheckBox(control: FormControl): { [s: string]: boolean } {
if (control.value === false) {
return {'checkBoxIsForbidden': true};
}
}