I have developed a custom input called formControl
, which requires me to fetch and set its value using [(ngModel)]:
import { Component, Injector, OnInit, forwardRef } from '@angular/core';
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR, FormGroup } from '@angular/forms';
@Component({
selector: 'time-picker',
template:
`<input type="text" class="clockpicker" [formControl]="selectedTime" />`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TimePickerComponent),
multi: true,
}]
})
export class TimePickerComponent implements OnInit, ControlValueAccessor {
selectedTime = new FormControl('');
constructor() { }
ngAfterViewInit() {
this.scriptLoader.load(
'assets/clockpicker/clockpicker.js'
);
}
writeValue(obj: any): void {
if (this.selectedTime) {
this.selectedTime.setValue(obj);
}
}
registerOnChange(fn: any): void {
this.selectedTime.valueChanges.subscribe(fn);
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
}
In the code above, I have imported an external JavaScript library named clockpicker.js
. This library is used for creating a simple clock picker feature. Here's the script for it:
$(document).ready(function () {
$('.clockpicker').each(function (index, element) {
$(element).clockpicker({
afterDone: function () {
$(element).find('input[type="text"]').change();
}
});
});
});
The issue here is that when I manually input text into the field, I can retrieve the value inserted via [(ngModel)]
. However, when the clockpicker function populates the field with a value, I cannot access that filled value using [(ngModel)]
.
This problem arises because the registerOnChange
event in Angular lifecycle does not get triggered even when I use
$(element).find('input[type="text"]').change();
No action is taken as a result.