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

前端 未结 1 1724
不知归路
不知归路 2021-01-28 00:59

I am trying to do smth like this

@Directive({
  selector: \'[myVal][myCustomInputToComponent]\',
  providers: [
    { provide: NG_VALIDATORS, useExisting: forwar         


        
相关标签:
1条回答
  • 2021-01-28 01:34

    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
      }
    }
    
    0 讨论(0)
提交回复
热议问题