How would you build a reusable custom form control?
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
- What is the difference between template-driven and reactive forms?
- How do you add validation to a reactive form?
- How do you write a custom validator?
- What are async validators and when do you need one?
- What are FormArray and dynamic forms?
- What is the difference between valueChanges and statusChanges, and how do you use them safely?