是否可以为自定义组件(不是FormControl)创建验证器

问题描述 投票:0回答:1

我想这样做

@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与客户进行交互,不是吗?

angular validation angular-directive
1个回答
1
投票

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

当然,你可以有一个组件,例如在更改为输入调用函数,但实际上不是验证

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

@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
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.