Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show suggestion on focus using PrimeNG autocomplete component

I would make autocomplete showing suggestion when user click on input field.

For the moment suggestions are showed only if user enter characters.

<p-autoComplete [formControl]="control.controls.EJ_Id_Name" 
  [suggestions]="results" 
  (completeMethod)="search($event,'EJ')" 
  emptyMessage={{noResult}} 
  [autoHighlight]="true">
</p-autoComplete>

I have tried to add (onFocus) and pass to it search($event,'EJ')

Here's my search function :

search(event, type) {
    this.searchRmpmService.getResults(event.query, type).then(data => {
        console.log(event);
        if(event.query){
            this.results = this.filterResults(event.query, data);
            console.log(this.results)
        }
        else {

            this.results = ["onfocus"];
            console.log(this.results) // I get "onfocus" on my devtool browser when I focus on the input            }

    });
}

onFocus() does not show me a suggestion list, I guess that I should call (completeMethod) in onFocus but I don't know how ?

like image 823
Hamza Haddad Avatar asked Mar 07 '18 13:03

Hamza Haddad


2 Answers

It may help if you need additionally to display suggestion when the input field of autocomplete is cleared. Therefore 2 events will be handled: onFocus and onClear. Here is the workaround:

In template bind onClear event with function clearItem():

<p-autoComplete ...
    #autocomplete
    (onFocus)="!autocomplete.value && autocomplete.handleDropdownClick()"
    (onClear)="clearItem(autocomplete)">
</p-autoComplete>

In component implement function clearItem() when onClear event is triggered:

clearItem(autocomplete: any) {
    autocomplete.value = '';  
    autocomplete.handleDropdownClick();  
}
like image 149
boisamazing Avatar answered Dec 02 '22 22:12

boisamazing


The autocomplete has the onFocus() event, you can show the suggestions by calling the .show() method.

<p-autoComplete  #autoComplete [formControl]="control.controls.EJ_Id_Name" 
  (onFocus)="autoComplete.show()"
  [suggestions]="results" 
  (completeMethod)="search($event,'EJ')" 
  emptyMessage={{noResult}} 
  [autoHighlight]="true">
</p-autoComplete>

Edit:

It seems like there a bug with the autocomplete, as a workaround you can try this

<p-autoComplete  #autoComplete [formControl]="control.controls.EJ_Id_Name" 
  (onFocus)="!autocomplete.value && autocomplete.handleDropdownClick()"
  [suggestions]="results" 
  (completeMethod)="search($event,'EJ')" 
  emptyMessage={{noResult}} 
  [autoHighlight]="true">
</p-autoComplete>

Source

like image 20
Kld Avatar answered Dec 02 '22 22:12

Kld