Why do I need call onChange and onTouch in writeValue when implementing ControlValueAccessor in Angular?
Read this article that explains the ControlValueAccessor
in great details:
- Never again be confused when implementing ControlValueAccessor in Angular forms
You usually need to implement ControlValueAcceessor
interface on a component if it's supposed to be used as part of an Angular form.
I commented out the second and third line of writeValue(...) method and, as far I can tell, nothing broke.
This is probably because you're not applying any form directive - formControl
or ngModel
that links a FormControl
to your custom input component. The FormControl
uses writeValue
method of the InputComponent
for communication.
Here is the picture from the article I referenced above:
The writeValue
method is used by formControl
to set value to the native form control. The registerOnChange
method is used by formControl
to register a callback that is expected to be triggered every time the native form control is updated. The registerOnTouched
method is used to indicate that a user interacted with a control.
Why is it important to execute the call to onChange(...) and onTouch(...) in writeValue(...)? What will go wrong and under what circumstances can it be expected?
This is the mechanism by which you custom control that implements ControlValueAcceessor
notifies the Angular's FormControl
that a value in the input has changed or the user interacted with the control.
...discovered that I couldn't tell anything going bananas when I removed setDisabledState(...)...Does it really need to be implemented?
As specified in the interface this function is called by the forms API when the control status changes to or from "DISABLED". Depending on the value, it should enable or disable the appropriate DOM element.
You need to implement it if you want to be notified whenever the status of an associated FormControl
becomes disabled
and then you can perform some custom logic (for example, disable your input component).