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

偶尔善良 提交于 2019-12-18 09:49:14

问题


I am trying to do smth like this

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

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?


回答1:


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


来源:https://stackoverflow.com/questions/54645878/is-it-possible-to-crate-a-validator-for-a-custom-component-not-for-a-formcontro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!