简体   繁体   中英

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 ?

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();  
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM