Implement Control Value Accessor methods
You’re going to need to implement the following methods and variables:
- onChange → the callback function to register on UI change
- onTouch → the callback function to register on element touch
- set value(val: any) → sets the value used by the ngModel of the element
- writeValue(value: any) → This will will write the value to the view if the the value changes occur on the model programmatically
- registerOnChange(fn: any) → When the value in the UI is changed, this method will invoke a callback function
- registerOnTouch(fn: any) → When the element is touched, this method will get called
Heres the implementation:export class CustomInputComponent implements ControlValueAccessor {constructor() { }onChange: any = () => {}onTouch: any = () => {}val= "" // this is the updated value that the class accessesset value(val){ // this value is updated by programmatic changes if( val !== undefined && this.val !== val){this.val = valthis.onChange(val)this.onTouch(val)}}// this method sets the value programmaticallywriteValue(value: any){ this.value = value}// upon UI element value changes, this method gets triggeredregisterOnChange(fn: any){this.onChange = fn}// upon touching the element, this method gets triggeredregisterOnTouched(fn: any){this.onTouch = fn}}
https://medium.com/@majdasab/implementing-control-value-accessor-in-angular-1b89f2f84ebf
ReplyDelete