我有一个mat-form-field
用于确认用户密码:
<mat-form-field>
<input matInput required placeholder="Gentag password" [type]="hidePassword ? 'password' : 'text'"
formControlName="confirmPassword" [errorStateMatcher]="passwordMatcher">
<mat-icon matSuffix (click)="hidePassword = !hidePassword">{{hidePassword ? 'visibility_off' : 'visibility'}}
</mat-icon>
<mat-error *ngIf="registerForm.hasError('mismatch') && !registerForm.hasError('required', 'confirmPassword')">De to passwords matcher ikke</mat-error>
<mat-error *ngIf="registerForm.hasError('required', 'confirmPassword')">Bekræft venligst passwordet</mat-error>
</mat-form-field>
这是我正在使用的errorStateMatcher
:
class PasswordErrorStateMathcer implements ErrorStateMatcher {
isErrorState(control: FormControl, form: import("@angular/forms").FormGroupDirective | import("@angular/forms").NgForm): boolean {
return !!((control && control.touched && control.parent && control.parent.invalid) || (form.submitted));
}
}
两个mat-errors
可以正常工作,但是当错误消失后,该字段将保持红色,好像仍然有错误:
在这里您可以看到控制台中打印的对象,它表明它是有效的:
这就是我创建FormGroup
的方式:
this.registerForm = this.builder.group({
firstName: ["", [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
lastName: ["", [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
email: ["", [Validators.required, Validators.pattern("[a-zA-Z0-9]{1,}([._-]?[a-zA-Z0-9]{1,})*@[a-zA-Z]{2,}([.-]{1}[a-zA-Z0-9]{1,})*[.]{1}[a-zA-Z]{2,}"),
Validators.maxLength(40)]],
checkboxGroup: new FormGroup({
adminCheckbox: new FormControl(false),
proCheckbox: new FormControl(false),
researcherCheckbox: new FormControl(false),
datamanagerCheckbox: new FormControl(false),
}, this.checkboxValidator),
password: ["", [Validators.minLength(6), Validators.maxLength(20)]],
confirmPassword: [""]}, { validator: this.confirmPasswordValidator, });
}
这是我的confirmPasswordValidator
:
confirmPasswordValidator(group: FormGroup) {
let pass = group.controls.password.value;
let confirmPass = group.controls.confirmPassword.value;
return pass === confirmPass ? null : { mismatch: true };
}
为什么它保持红色?
答案 0 :(得分:0)
ErrorStateMatcher检查父表单状态,
return !!((control && control.touched && control.parent && control.parent.invalid) || (form.submitted));
确保父表单有效或已提交。
要在输入有效数据后消除错误,请更改您的ErrorStateMatcher函数
return !!((control && control.touched && control.invalid) || (form.submitted));