Angular provides a powerful form validation library (both Vue and React require third-party library support) that makes it easy to implement form validation in Web applications. But how do we get our custom components to support validation as well?

I came across a requirement to wrap the WangEditor rich text editor into a form.

This requirement is very common. Angular provides the ControlValueAccessor interface that makes it easy to implement custom validation

Understand ControlValueAccessor

Officially, ControlValueAccessor acts as a bridge between Angular forms apis and native elements in the DOM

This interface provides four methods

interface ControlValueAccessor {
  writeValue(obj: any) :void
  registerOnChange(fn: any) :void
  registerOnTouched(fn: any) :void
  setDisabledState(isDisabled: boolean)? :void
}

Copy the code

In general, only the writeValue and registerOnChange methods need to be handled

WriteValue is a formGroup that passes a value to a custom component that needs to handle the display state based on this value.

The parameter to registerOnChange is a Function that needs to be called to pass the value of the component to the formGroup when the component state changes

Register the Provider to validate the current interface processing

If you simply implement this interface, it will not take effect. The NG_VALUE_ACCESSOR value needs to be unregistered as the current component in the module registry or in the Attribute on the component.

  providers: [{
    provide: NG_VALUE_ACCESSOR, useExisting: QWangEditorComponent, multi: true
  }]

Copy the code

Once this is done, the component supports Angular form validation.

By adding the formControlName attribute to the form, the custom component’s functionality can be bidirectionally bound to the corresponding attribute in the formGroup and supports form validation.

The last

Welcome to pay attention to my public account [Qingcheng classmates], and share my technical and non-technical things with you from time to time