I had found a solution an year ago and updating my answer for others.
As stefan's
answer we need model mapping, but his answer looks large process.
I used primeng autocomplete component and created a own component called user-search
with @Input()
and @Output()
events.
Template (user.search.component.html)
<p-autoComplete [(ngModel)]="userObject" placeholder="User Search..." field="user_name" [suggestions]="userSuggesstionList"
(onSelect)="onUserSelect($event)" (completeMethod)="search($event)">
</p-autoComplete>
Component (UserSearchComponent ),
@Component({
selector: 'user-search',
templateUrl: 'user.search.component.html'
})
export class UserSearchComponent implements OnInit {
userSuggesstionList: any[] = [];
userObject: any;
constructor(
) { }
ngOnInit() {
}
// note that this must be named as the input model name + "Change"
@Output() userSelected: any = new EventEmitter();
@Output() userIdChange: any = new EventEmitter();
@Input()
set userId(userId: string) {
if (userId != null && userId != '') {
this.userObject = // Load user object from local cache / from service.
} else {
this.userObject = null;
}
}
get userId(): string {
if (this.userObject != null) {
return this.userObject.userId;
} else {
return null;
}
}
search(event) {
// your search logic.
}
onUserSelect(event) {
this.userIdChange.emit(event.userId);
this.userSelected.emit(event);
}
}
And the usage of user-search component is,
<user-search [(userId)]="user_id"></user-search>
Here the user_id given as input to user-search
component, user-search
component loads actual user object from cache/ from server as based on user_id
. once the user object gets loaded then p-autocomplete
will bind with userObject
and displayed the username in autocomplete box.
Once user selected from suggestion list, A default change event is triggered to update user_id
value in parent component.
Also you can avail the UserObject ie. {user_id: 'xxx', user_name:'xxx'} in userSelected
event.