从angular指令返回自定义错误

时间:2017-12-15 13:01:30

标签: angular

根据我到目前为止所学到的,验证错误是用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中返回的是输入的工资不能低于(数值),因为该值可以从指令获得

1 个答案:

答案 0 :(得分:1)

返回的错误可以包含您想要的任何数据。

所以如果你回来了

 return {
      lowSalary: {
        valid: false,
        oldSalary: Number(this.oldSalary)
      }
    }

您可以在模板中使用它

<span *ngIf="salVar.errors.lowSalary">
    Salary entered cannot be lesser than {{salVar.errors.lowSalary.oldSalary}}.
 </span>