是否可以为自定义组件(而不是 FormControl)创建验证器 [英] Is it possible to crate a Validator for a custom component (not for a FormControl)

查看:30
本文介绍了是否可以为自定义组件(而不是 FormControl)创建验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做

@Directive({
  selector: '[myVal][myCustomInputToComponent]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => MyVal), multi: true }
  ]
})
export class MyVal implements OnInit, Validator {

  @Input() input: any;

  constructor(private el: ElementRef) {
  }
  ngOnInit(): void {
    console.log('validator input', this.input);

  }

  validate(): { [key: string]: any } {
    console.log('validate', this.input)

    return {
      validatorName: {
        valid: false
      }
    };
  }
}

而且validate 方法显然没有被调用.但也许有一些方法可以检测具有有效和无效状态的组件.我们不是只使用 FormControls 与客户进行交互,innit?

And validate method obviously was not called. But maybe there is some way how you detect components with valid and invalid state. We are not using only FormControls to interact with customer, innit?

推荐答案

Karina,您无法验证任何组件.您可以验证一个特殊的组件:自定义表单控件.在自定义表单控件中,您可以在自定义表单控件内部或外部创建验证器.但这必须实现 ControlValueAccessor.

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

如果您的自定义表单控件在控件内有一个验证器,您的自定义表单控件必须添加为提供程序 NG_VALIDATORS,并且会像

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
  }
}

这篇关于是否可以为自定义组件(而不是 FormControl)创建验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆