I am trying to wrap a ng-select (https://github.com/ng-select/ng-select) component with a custom component, I am using ControlValueAccessor with a reactive form,
export class ShNgSelectComponent implements OnInit, OnChanges,
ControlValueAccessor {
@Input() shItems: Array<object>;
@Input() shBindValue: string;
@Input() shBindLabel: string;
@Input() shPlaceholder: any;
@Output() shChange = new EventEmitter<Object>();
ngOnInit() {
}
writeValue(value: any): void {
this.shItems = value || '';
}
propagateChange(event){
this.shChange.emit(event);
}
registerOnChange(fn) {
this.propagateChange = fn;
}
registerOnTouched() { }
}
here is the template for the sh-ng-select
<ng-select [items]='shItems' [bindValue]='shBindValue' [placeholder]='shPlaceholder' [bindLabel]='shBindLabel' (change)='propagateChange($event)'></ng-select>
and here is the main component where i want to embed my custom component
<sh-ng-select [shItems]='manufactureList' [shFormGroup]='requestForm' (shChange)='getModels($event)' formControlName="manufactureId" [shPlaceholder]='"اختر الشركة المصنعة"' [shBindValue]='"id"' [shBindLabel]='"name"'></sh-ng-select>
the shChange event fires normally before i add the formControlName, but once I do the event does not fire, and the console does not throw any error......why is that?
For me when you add the formControlName it bind everything it need to work, so it will call the registerOnChange , registerOnTouched, writeValue... since he call the registerOnChange and do "this.propagateChange = fn" the propageChange method will no longer reference the one you define :
propagateChange(event){
this.shChange.emit(event);
}
So the shChange event emitter is not called anymore
For more information, making components working with [(ngModel)] / formControlName repeat the same pattern, here you can find a simple implementation that you could extend to use in your component : https://github.com/xrobert35/asi-ngtools/blob/master/src/components/common/default-control-value-accessor.ts
A simple component using it : https://github.com/xrobert35/asi-ngtools/blob/master/src/components/asi-checkbox/asi-checkbox.component.ts