How would you build a reusable custom form control?

Angular forms · Experienced

Model answer

Implement ControlValueAccessor in a component and register it with NG_VALUE_ACCESSOR. The interface has writeValue (the form gives your component a value), registerOnChange (you call it when the user changes the value), registerOnTouched and setDisabledState.

After that, your component works with ngModel, formControl and formControlName like a native input. Good examples: a star rating, a date picker wrapper or a tag input. Keep the component's inner state simple and make sure the touched state is reported on blur.

Learn this topic

Angular Tutorial: Beginner to Advanced .

Sign in to add your own answer.

More questions