Suppose I want to create a custom form control. Is it possible to achieve this?
<custom-control [ngModel]="myModelVariable" (ngModelChange)="modelHasChanged($event)"></custom-control>
I've successfully implemented [(ngModel)] with all the form controls I've developed, but I'm facing issues with detecting changes. Many users of my components require this feature, and I am curious if there is a cleaner solution without using @Output EventEmitters. It seems like there might be a mistake in my approach, or perhaps I need to rethink my strategy.
Here is an example component implementation based on my understanding:
@Component({
selector: 'custom-control',
providers: [
{ provide: NG_VALUE_ACCESSOR, useClass: CustomControlComponent, multi: true }
]
})
export class CustomControlComponent implements ControlValueAccessor {
private onChangeCallback: (_: any) => void = (_: any) => {};
private onTouchedCallback: () => void = () => {};
private innerValue: any;
get value(): any {
return this.innerValue;
}
set value(val: any) {
if (val !== this.innerValue) {
this.innerValue = val;
this.onChangeCallback(this.innerValue);
}
}
writeValue(val: any) {
if (val !== this.innerValue) {
this.innerValue = val;
}
}
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
}