My Angular 10 project includes a library with a wrapper component around a primeng-component. The primeng-component utilizes ngModel
. I am trying to set the ngModel
in the parent-component accessing the wrapper-component, and I want any changes made to the ngModel
within the primeng-component to be reflected back in the parent-component.
This is how the parent-component incorporates the wrapper:
parent.component.html
<div class="col">
<wrapper-autocomplete
[suggestions]="projects"
ngDefaultControl
[ngModel]="selectedProject"
(ngModelChange)="changeSelectedProject($event)"
[field]="'name'"
(completeMethod)="getProjects($event)"
[forceSelection]="true">
...
</wrapper-autocomplete>
</div>
In the parent-component, the [ngModel]
is set to a variable named selectedProject
, which triggers a change through ngModelChange
event calling a custom function:
parent.component.ts
changeSelectedProject(event: any) {
this.selectedProject = event;
}
The wrapper-component includes the primeng-component as follows:
wrapper.component.html
<p-autoComplete
...
[ngModel]="ngModel"
(ngModelChange)="ngModelChangeCallback($event)">
...
</p-autoComplete>
The TypeScript portion of the code is structured like this:
wrapper.component.ts
@Component({
selector: 'wrapper-autocomplete',
templateUrl: './autocomplete-list.component.html',
styleUrls: ['./autocomplete-list.component.css']
})
export class AutocompleteListComponent {
@Input() ngModel: any;
@Output() ngModelChange: EventEmitter<any> = new EventEmitter<any>();
ngModelChangeCallback(event: any): void {
this.ngModelChange.emit(event);
}
}
Although the current setup effectively reflects changes back to the parent-component, it is not the ideal approach for future users. I aim to simplify the model binding process by enabling users to bind the model using [(ngModel)]
instead of [ngModel]
and (ngModelChange)=...
.
Any insights on where I might be going wrong would be greatly appreciated. I have looked into the ControlValueAccessor feature, but I struggled to implement it correctly in my code.
Thank you for your help!