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

查看:201
本文介绍了是否可以为自定义组件(而不是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方法显然没有被调用.但是,也许可以通过某种方式来检测具有有效和无效状态的组件.我们不仅仅使用FormControl与客户进行互动吗?

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天全站免登陆