Javascript 角度自定义验证器不';不能反映观点的变化
我有这样的自定义验证器:Javascript 角度自定义验证器不';不能反映观点的变化,javascript,angular,ionic-framework,angular-forms,Javascript,Angular,Ionic Framework,Angular Forms,我有这样的自定义验证器: export class PasswordValidator { static MatchPassword(AC: AbstractControl) { const formGroup = AC.parent; if(formGroup) { let password = formGroup.value.password // to get value in input tag l
export class PasswordValidator {
static MatchPassword(AC: AbstractControl) {
const formGroup = AC.parent;
if(formGroup) {
let password = formGroup.value.password // to get value in input tag
let confirmPassword = formGroup.value.confirmPassword; // to get value in input tag
if(password != confirmPassword) {
formGroup.get('confirmPassword').setErrors({ matchPassword: true });
} else {
formGroup.get('confirmPassword').setErrors(null);
}
console.log(formGroup.get('confirmPassword').errors);
} else {
return null
}
}
}
我在表格中添加了:
this.registerationForm.addControl("confirmPassword", new FormControl('', Validators.compose([Validators.required, PasswordValidator.MatchPassword])));
鉴于:
<ion-item class="error-message" *ngIf="registerationForm.controls.confirmPassword.hasError('matchPassword')
&& registerationForm.controls.confirmPassword.touched">
<p>Some message*</p>
</ion-item>
一些信息*
但问题是我可以看到控制台窗口,但我看不到它在视图中的反射。当您在angular运行其更改检测后更新模型,或者如果更新根本不在angular world中时,ngIf
条件未显示错误消息使用detectChanges()
如果您使用的是OnPush,并且通过改变某些数据绕过了ChangeDetectionStrategy,或者您在setTimeout内更新了模型,请使用markForCheck()
export class PasswordValidator {
static MatchPassword(AC: AbstractControl) {
const formGroup = AC.parent;
if(formGroup) {
let password = formGroup.value.password // to get value in input tag
let confirmPassword = formGroup.value.confirmPassword; // to get value in input tag
if(password != confirmPassword) {
formGroup.get('confirmPassword').setErrors({ matchPassword: true });
} else {
formGroup.get('confirmPassword').setErrors(null);
}
console.log(formGroup.get('confirmPassword').errors);
this.ref.markForCheck();
} else {
return null
}
}
}
添加此.ref.markForCheck();更新表单后。我将如何将其注入此静态方法?是否为相同的方法创建了JSFIDLE?我认为这不是更改检测的问题。我已经在角度范围内了。从'@angular/core'导入{ChangeDetectorRef}时还丢失了其他内容;并将其注入MatchPassword,就像您为AC所做的一样。我认为它应该可以工作,我也有同样的问题,并因此得到解决。试试看,不能注射。它是纯静态类。根据这篇文章,它应该在没有它的情况下工作。