Angular 如何为模板驱动表单的交叉字段验证编写指令
所以我想创建一个验证器密码和确认密码(两个字段的值应该相同) 这可以通过创建一个Cross字段验证程序来实现,该验证程序获取这两个FormControl并比较它们的值 然后,我可以在我的组件中设置一种反应式表单方式:Angular 如何为模板驱动表单的交叉字段验证编写指令,angular,angular7,Angular,Angular7,所以我想创建一个验证器密码和确认密码(两个字段的值应该相同) 这可以通过创建一个Cross字段验证程序来实现,该验证程序获取这两个FormControl并比较它们的值 然后,我可以在我的组件中设置一种反应式表单方式: this.passwordForm = this.fb.group({ password: new FormControl(undefined, [Validators.required]), confirmPassword: new FormContro
this.passwordForm = this.fb.group({
password: new FormControl(undefined, [Validators.required]),
confirmPassword: new FormControl(undefined, [Validators.required])
}
, {validator: fieldMatcherValidator('password', 'confirmPassword')}
);
----上述代码以反应形式完美地工作
我的问题是:如何为验证器编写一个指令,以便我也可以以模板驱动的方式使用它
我试图编写如下指令,但这个验证器不应该在formControl上工作,而应该在formGroup上工作。以下指令无法获取formGroup及其控件,因此无法验证formControls值
@Directive({
selector: '[cmFieldMatcher]',
providers: [
{provide: NG_VALIDATORS, useExisting: FieldMatcherDirective, multi: true}
]
})
export class FieldMatcherDirective implements Validator {
@Input() field1: string;
@Input() field2: string;
validator: ValidatorFn;
constructor() {
this.validator = fieldMatcherValidator(this.field1, this.field2);
}
validate(control: AbstractControl) {
return this.validator(control);
}
}
当我在这样的模板中使用它时,我没有幸得到abstractControl实例
<form #form="ngForm" cmFieldMatcher [field1]="'password2'" [field2]="'confirmPassword2'">
<cm-form-field>
<cm-password-input name="password2" ngModel #password2="ngModel" [label]="'Password'" required [strengthLevel]="passwordStrength" [messages]="passwordMessages">
</cm-password-input>
<cm-form-field-error key="fieldMatch" [message]="'Password doesnt match'"></cm-form-field-error>
</cm-form-field>
<cm-form-field>
<cm-input [type]="'password'" name="confirmPassword2" ngModel #confirmPassword2="ngModel" required [label]="'Confirm Password'" [theme]="'primary'">
</cm-input>
<cm-form-field-error key="fieldMatch" [message]="'Password doesnt match'"></cm-form-field-error>
</cm-form-field>
</form>
更改此行:
useExisting: forwardRef(() => FieldMatcherDirective)
并从@angular/core导入
此外,它也不起作用,因为您在构造函数中得到了验证器fn。field1和field2输入总是未定义的,因为它们是在调用ngOnChanges钩子之前设置的。相反,请将该代码移动到ngonchange,如下所示:
ngOnChanges() {
this.validator = fieldMatcherValidator(this.field1, this.field2);
}
并将validate()方法更改为:
validate(control: AbstractControl) {
return this.validator ? this.validator(control) : null;
}
还是不走运。。告诉我错误:“this.validator不是函数”,返回this.validator(控件)
validate(control: AbstractControl) {
return this.validator ? this.validator(control) : null;
}