I have implemented the following component. It works and behaves as expected. Nevertheless, as the implementation of ControlValueAccessor
was new to me, I had to follow a blog without understanding the deeper details of a few sections. So this is a type of "it works but why?!" situation.
@Component({ selector: ..., templateUrl: ..., styleUrls: ...,
providers: [{ provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputTextComponent),
multi: true }]
})
export class InputComponent implements ControlValueAccessor {
constructor() { }
@Input() info: string;
onChange: any = () => { }
onTouch: any = () => { }
writeValue(input: any): void {
this.info.value = input;
// this.onChange(input);
// this.onTouch();
}
registerOnChange(_: any): void { this.onChange = _; }
registerOnTouched(_: any): void { this.onTouch = _; }
setDisabledState?(state: boolean): void { }
onEdit(value: string): void { this.onChange(value); }
}
When I've got it working, I commented out the second and third line of writeValue(...)
method and, as far I can tell, nothing broke. Those calls are consistently suggested by other blogs as well, so I'm convinced that it's improper to omit them. However, I don't believe in magic and prefer to have a concrete reason for doing things.
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?
As a side quest, I also tried to comment out the other methods and discovered that I couldn't tell anything going bananas when I removed setDisabledState(...)
. When can that one be expected to cause problems? Does it really need to be implemented (I've seen version with question mark both before and after the parentheses with parameters like so: setDisabledState?(state: boolean): void { }
but also like this: setDisabledState(state: boolean)?: void { }
).
Why is it important to execute the call to onChange(...) and onTouch(...) in writeValue(...)?
Where did you see it? – DunavilleregisterOnChanged
is called first time by the formControl the passed callback is stored toonChange
. Then it's called every time the custom control value is updated "from the inside" – Capetian