我定义了一个如下所示的自定义验证器
import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, FormControl } from '@angular/forms';
function validateRewardAmountFactory(goalAmount: number, quantity: number) {
return (c: FormControl) => {
const rewardAmount = c.value;
const isValidAmount = rewardAmount * quantity < goalAmount ? true : false;
return isValidAmount ? null : { validateAmount: true };
};
}
@Directive({
selector: '[validateAmount][ngControl][validateAmount][ngModel],[validateAmount][ngFormControl]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => RewardAmountValidator), multi: true }
]
})
export class RewardAmountValidator {
validator: Function;
constructor(goalAmount: number, quantity: number) {
this.validator = validateRewardAmountFactory(goalAmount, quantity);
}
validate(c: FormControl) {
return this.validator(c);
}
}
然后我在我的模块中声明了这个指令
@NgModule({
declarations: [RewardAmountValidator, ...]
})
现在我想在我的 react 形式中使用这个自定义验证器,我是这样做的
return this.fb.group({
'id': [project.id, Validators.required],
'type': ['reward', Validators.required],
'rewardAmount': ['', validateAmount(this.goalAmount, this.quantity)]
});
但它给我错误 Cannot find name 'validateAmount'
那么在我的响应式(Reactive)表单中使用自定义验证器的正确方法是什么。
最佳答案
试试这个:
return this.fb.group({
'id': [project.id, Validators.required],
'type': ['reward', Validators.required],
'rewardAmount': ['', Validators.compose(validateAmount(this.goalAmount, this.quantity))]
});
关于angular - 如何以 Angular react 形式使用自定义验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43846047/