【发布时间】:2019-02-21 04:01:19
【问题描述】:
我有一个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 };
}
为什么它一直是红色的?
【问题讨论】:
-
Stackblitz 示例?
标签: angular forms validation angular-material