我想知道如何检查该复选框是否被选中,如果未选中,则会为用户显示一条错误消息。我设法放置了错误消息,但无法将其与表单的其余部分一起使用。你能帮助我吗?这就是我要做的。
<mat-checkbox class="hcs-full-width" [formControl]="termsFormControl"> Aceite os termos de uso
</mat-checkbox>
<mat-error *ngIf="termsFormControl.hasError('required')">
Termo é
<strong>requirido</strong>
</mat-error>
.ts
export class AppComponent implements OnInit {
private subscription: Subscription;
uri: string;
ssid: string;
sessiondId: string;
ip: string;
mac: string;
ufi: string;
mgmtBaseUrl: string;
clientRedirectUrl: string;
req: string;
userName: string;
hmac: string;
name: string;
email: string;
constructor(@Inject(DOCUMENT) private document: any, private route: ActivatedRoute) {
}
ngOnInit() {
this.route.queryParams
.filter(params => params.mac)
.subscribe(params => {
console.log(params);
this.ssid = params.ssid;
this.sessiondId = params.sessionId;
this.ip = params.ip;
this.mac = params.mac;
this.ufi = params.ufi;
this.mgmtBaseUrl = params.mgmtBaseUrl;
this.clientRedirectUrl = params.clientRedirectUrl;
this.req = params.req;
this.hmac = params.hmac;
});
console.log("LOGAR: " + this.nameFormControl.valid);
console.log("LOGAR: " + this.termsFormControl.valid);
}
Logar() {
if (this.nameFormControl.valid && this.emailFormControl.valid && this.termsFormControl.valid) {
this.userName = this.name + ";" + this.email;
this.uri = "#" + this.ssid + "&sessionId=" + this.sessiondId + "&ip=" + this.ip + "&mac=" + this.mac + "&ufi=" + this.ufi + "&mgmtBaseUrl=" + this.mgmtBaseUrl + "&clientRedirectUrl=" + this.clientRedirectUrl + "&req=" + this.req + "&username=" + this.userName + "&hmac=" + this.hmac;
// console.log("LOGAR: " + this.nameFormControl.valid);
this.document.location.href = this.uri;
}
console.log("LOGAR: " + this.nameFormControl.valid);
console.log("LOGAR: " + this.termsFormControl.valid);
};
emailFormControl = new FormControl('', [
Validators.required,
Validators.email,
]);
nameFormControl = new FormControl('', [
Validators.required,
]);
termsFormControl = new FormControl('', [
Validators.required,
]);
}
Checkbox不能那样工作,您必须实现自定义验证程序并将其分配给termsFormControl
。在您的情况下,它将是:
termsFormControl = new FormControl('', [(control) => {
return !control.value ? { 'required': true } : null;
}]
);
在这里,自定义验证器会明确检查控件的值,如果为false,则将required
error设置为true
。这样,您可以将状态设置为表单,并可以使用强大的功能。
请参阅GitHub上的以下问题以获取更多解释,为什么您必须实施自定义验证。
编辑1
要在单击按钮时显示错误消息,您可以将条件设置为在复选框无效且脏时增加错误:
<mat-error *ngIf="termsFormControl.invalid && termsFormControl.dirty">
Termo é <strong>requirido</strong>
</mat-error>
然后在按钮上单击,您可以将复选框设置为脏(我看不到您的完整代码,但是应该是这样的):
onSubmit() {
this.form.get('termsFormControl ').markAsDirty();
}
编辑2
基于@Julida,内置的验证器 建议Validators.requiredTrue
可用于复选框元素。它确认是否选中了复选框。如果未选中,则将控件标记为无效。
kat1330感谢您的答复,但是我想知道如何使错误消息仅在用户单击按钮且未选中复选框时出现。
@Mark我更新了答案。基本上,我扩展了HTML中的大小写以显示消息,如果控件无效且不干净。然后在按钮上单击我将控件标记为脏。
@ kat1330为什么不使用内置验证器“ requiredTrue”?
termsFormControl = new FormControl(false, Validators.requiredTrue)