获得
从我到目前为止所学到的东西,验证错误是用html编写的,但是如何返回自定义错误。例如,我有下面的指令
@Directive({
selector: '[verifySalaryUp]', // Attribute selector
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => VerifySalaryUpDirective), multi: true }
]
})
export class VerifySalaryUpDirective implements Validator {
@Input('status') status: any;
@Input('oldSal') oldSalary;
constructor() {
}
validate(control: AbstractControl): {[key: string]: any} {
let newSalary = control.value;
if (this.status === 'N') {
return null;
} else {
if (Number(newSalary) < Number(this.oldSalary)) {
return {
lowSalary: {
valid: false
}
}
} else {
return null;
}
}
}
}
HTML部分如下
<span *ngIf="salVar.errors.lowSalary">Salary entered cannot be lesser than the previously entered salary.</span>
,但我想在HTML中返回的是,输入的薪金不能比(数字值)更小,因为该值可以从指令
返回的错误可以包含您想要的任何数据。
所以如果您返回
return {
lowSalary: {
valid: false,
oldSalary: Number(this.oldSalary)
}
}
您可以在模板中使用它
<span *ngIf="salVar.errors.lowSalary">
Salary entered cannot be lesser than {{salVar.errors.lowSalary.oldSalary}}.
</span>