Currently, I am in the process of creating a custom form component using Angular 4. I have included all necessary components for ngModel to function properly, but unfortunately, it is not working as expected.
Below is an example of my child component:
export class Search extends ControlValueComponent {
}
This component extends from the ControlValueComponent class, which manages all aspects of "ControlValueAccessor".
Here is the ControlValueAccessor class:
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";
import {forwardRef, Input} from "@angular/core";
export class ControlValueComponent implements ControlValueAccessor {
@Input() disabled: boolean;
innerValue: any = '';
static providerValueAcessor( ref: any): any {
return [
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => ref), multi: true }
];
}
onTouchedCallback: () => void = () => {};
onChangeCallback: (_: any) => void = () => {};
constructor() {
}
get value(): any {
return this.innerValue;
}
set value(v: any) {
if (v !== this.innerValue) {
this.innerValue = v;
this.onChangeCallback(v);
}
}
writeValue(value: any) {
if (value !== this.innerValue) {
this.innerValue = value;
}
}
registerOnChange(fn: any): void {
this.onChangeCallback = fn;
}
registerOnTouched(fn: any): void {
this.onTouchedCallback = fn;
}
}
In order to ensure that the provider is correctly implemented, I utilize the ProviderValueAccesor function (found within the ControlValueComponent) like this
providers: ControlValueComponent.providerValueAcessor(SysSearch)
However, despite having [(ngModel)] added to my child component, it continues to display an error stating that ngModel is not recognized as a property of the component.
I attempted to use it in the following manner:
<search [(ngModel)] = 'value'><search>