So, i'm trying to make a custom form component in angular 4, i added everything needed for the ngModel to work but it doesnt.
This is my child component:
export class Search extends ControlValueComponent {
}
It extends to the class ControlValueComponent that handles all the "ControlValueAccesor".
This is the class ControlValueAccesor:
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;
}
}
And in order to have the provider right i use the function ProviderValueAccesor (that is in the ControlValueComponent) like this
providers: ControlValueComponent.providerValueAcessor(SysSearch)
But when i add to my child component the [(ngModel)] it keeps getting the error that ngModel is not a property of the component
I try to use it like this:
<search [(ngModel)] = 'value'><search>
I already fixed the problem.
I needed to import FormsModule directly on the parent component that calls the child component in order for the ngModel to work... I did it like this:
import {FormsModule} from "@angular/forms";
@NgModule({
imports: [
FormsModule,
SearchModule
]
This way, the father component is able to use the ngmodel property. Thanks for the help