Search code examples
htmlangularautocompletedropdownprimeng

Angular/Primeng - Implement p-autocomplete dropdown with no button


I have a "p-autocomplete" element with multiple entries and dropdown enabled, and am wondering if I can do so without displaying the button, but instead show the dropdown menu when users click on the autocomplete field.

Is this possible with this type of object?

I am using Primeng version 4.3.0, if it makes a difference.

HTML:

<p-autoComplete id="input-country" [multiple]="true" [(ngModel)]="selectedCountries" [dropdown]="true"
          [suggestions]="filteredCountries" (completeMethod)="filterCountryMultipe($event)">
                 <ng-template let-selectedCountries pTemplate="item">
                 ....
          </ng-template>
 </p-autoComplete>

=================== UPDATE===================== Thank you to olivier-depriester for your answer below. In addition to the onFocus method, I also removed the dropdown property and handled everything with the autocomplete, simply amending the filter method to accept an empty query.

Current HTML:

<p-autoComplete id="input-country" [multiple]="true" [(ngModel)]="selectedCountries" (onFocus)="onFocus()"
                    [suggestions]="filteredCountries" (completeMethod)="filterCountryMultiple($event)" >
                <ng-template let-selectedCountries pTemplate="item">
                    ....
                </ng-template>
            </p-autoComplete>

Current Typescript:

onFocus(){
    this.filterCountryMultiple({query:''});
    this.autoComplete.show();
}

filterCountryMultiple(event) {
    let query = event.query;
    this.filteredCountriesMultiple = this.filterCountry(query);
}

filterCountry(query):any[] {
....
    for(let i = 0; i < countries.length; i++) {
        let country = countries[i];
        if(...query is empty...){
            filtered.push(country.code);
        }
        else if(...match found...) {
            filtered.push(country.code);
        }
    }
    return filtered;
}

Solution

  • With primeng 6.5 to 7.0, I used the show function, bound on the focus event.

    On typescript side :

    export class MyComponent {
        @ViewChild(AutoComplete) private autoComplete: AutoComplete;
    
        onFocus() {
            this.autoComplete.show();
        }
    }
    

    And on HTML side :

    <p-autoComplete id="input-country" [multiple]="true" [(ngModel)]="selectedCountries" [dropdown]="true"
        [suggestions]="filteredCountries"
        (completeMethod)="filterCountry($event)"
        (onFocus)="onFocus($event)">
             <ng-template let-selectedCountries pTemplate="item">
                 <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">
                       .......
             </ng-template>
    </p-autoComplete>
    

    But in primeng current version (v8), this method is no more documented. So I don't know if it still exists