Is it possible to crate a Validator for a custom component (not for a FormControl)

我怕爱的太早我们不能终老 提交于 2019-11-29 17:34:37

Karina, you can not validate any component. You can validate a especial component: a custom form control. In a custom form control, you can create a validator, inside or outside the custom form control. But this must ve implements ControlValueAccessor.

Of couse you can has a component and e.g. in chenge to an input call a function, but really is not a validation

If your custom form Control has a validator inside the control your custom form control must add as provider NG_VALIDATORS, and will be like

@Component({
  selector: 'app-custom-form-control',
  template: `...
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomFormControl),
      multi: true
    },
    {
  provide: NG_VALIDATORS,
  useExisting: forwardRef(() => CustomFormControl),
  multi: true,
}
  ]

})
export class CustomFormControl implements ControlValueAccessor {

  onChange;
  onTouched;

  constructor(el:ElementRef){}
  writeValue(value: any[]|any): void {
        ...receive a value, make something to show it...
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
  }

  //A function that, when some happens, send a change
  setValue(value: any) {
    this.onChange(...)
  }

  focusOut()
  {
    this.onTouched()
  }

  validate(control: AbstractControl): ValidationErrors | null{
     ..your logic here..
    return null
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!