我正在尝试为创建自定义验证器mat-input
。一切正常,在发生错误时显示错误,但在解决错误后,mat-form-field
不会删除mat-form-field-invalid
类https://imgur.com/a/MSsaVop
class CrossFieldErrorMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective |
NgForm | null): boolean {
return control.dirty && form.invalid;
}
}
errorMatcher = new CrossFieldErrorMatcher();
register = this.fb.group({
userName: ['', [Validators.required]],
userEmail: ['', [Validators.required, Validators.email]],
phone: ['', [Validators.required, this.phoneNumberValidator]],
userPassword: ['', [Validators.required]],
passwordconfirm: ['', ],
adminName: ['', [Validators.required]],
adminPassword: ['', [Validators.required]],
}, {
validator: this.passwordValidator
})
passwordValidator(form: FormGroup) {
const condition = form.get('passwordconfirm').value !==
form.get('userPassword').value;
return condition ? { passwordsDoNotMatch: true } : null;
}
<mat-form-field class=" my-4 ">
<input matInput type="password" required
formControlName="userPassword" placeholder="Password"
[type]="hide ?'password' : 'text'" class="col-4" name="password">
</mat-form-field>
<mat-form-field class=" my-4 ">
<input matInput type="password" required
formControlName="passwordconfirm" placeholder="Confirm
Password"
[type]="hide2 ? 'password' : 'text'" class="col-4"
[errorStateMatcher]="errorMatcher" name="conpassword">
<mat-error *ngIf="register.hasError('passwordsDoNotMatch')">
Passwords do not match!
</mat-error>
</mat-form-field>
问题在于CrossFieldErrorMatcher
,当您真正想要的只是查看该表单的子集时,您正在使用整个表单来验证密码。
要解决此问题,只需FormGroup
为passwords元素添加一个单独的名称,以便您的表单构建如下所示:
register = this.fb.group({
userName: ['', [Validators.required]],
userEmail: ['', [Validators.required, Validators.email]],
phone: ['', [Validators.required, this.phoneNumberValidator]],
// Create a separate FormGroup here to isolate the scope
passwords: this.fb.group({
userPassword: ['', [Validators.required]],
passwordconfirm: [''],
}, { validator: this.passwordValidator }),
adminName: ['', [Validators.required]],
adminPassword: ['', [Validators.required]]
})
然后在您的模板中,只需将您的密码元素“包装”在中div
,FormGroup
就可以FormGroup
像这样指定新内容:
<div [formGroup]="register.get('passwords')"> // Assign the new FormGroup
<mat-form-field class=" my-4 ">
<input matInput type="password" required
formControlName="userPassword" placeholder="Password"
[type]="hide ?'password' : 'text'" class="col-4" name="password">
</mat-form-field>
<mat-form-field class=" my-4 ">
<input matInput type="password" required
formControlName="passwordconfirm" placeholder="Confirm Password"
[type]="hide2 ? 'password' : 'text'" class="col-4"
[errorStateMatcher]="errorMatcher" name="conpassword">
<mat-error *ngIf="register.get('passwords').hasError('passwordsDoNotMatch')">
Passwords do not match!
</mat-error>
</mat-form-field>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句