AutoComplete AutoComplete is an input component that provides real-time suggestions when being typed.

Basic

Country: {{country ? country.name||country : 'none'}}

Advanced

{{brand}}
Brand: {{brand||'none'}}

Multiple

Import


import {AutoCompleteModule} from 'primeng/autocomplete';

Getting Started

AutoComplete uses ngModel for two-way binding, requires a list of suggestions and a completeMethod to query for the results. The completeMethod gets the query text as event.query property and should update the suggestions with the search results.


<p-autoComplete [(ngModel)]="text" [suggestions]="results" (completeMethod)="search($event)"></p-autoComplete>


export class AutoCompleteDemo {

    text: string;

    results: string[];

    search(event) {
        this.mylookupservice.getResults(event.query).then(data => {
            this.results = data;
        });
    }

}

Change Detection

AutoComplete either uses setter based checking or ngDoCheck to realize if the suggestions has changed to update the UI. This is configured using the immutable property, when enabled (default) setter based detection is utilized so your changes such as adding or removing a record should always create a new array reference instead of manipulating an existing array as Angular does not trigger setters if the reference does not change. For example, use slice instead of splice when removing an item or use spread operator instead of push method when adding an item. On the other hand, setting immutable property to false removes this restriction by using ngDoCheck with IterableDiffers to listen changes without the need to create a new reference of data. Setter based method is faster however both methods can be used depending on your preference.

Model Driven Forms

AutoComplete can be used in a model driven form as well.


<p-autoComplete formControlName="city" [suggestions]="results" (completeMethod)="search($event)"></p-autoComplete>

Dropdown

Enabling dropdown property displays a button next to the input field where click behavior of the button is defined using dropdownMode property that takes "blank" or "current" as possible values. "blank" is the default mode to send a query with an empty string whereas "current" setting sends a query with the current value of the input.


<p-autoComplete [(ngModel)]="text" [suggestions]="results" (completeMethod)="search($event)"
            [dropdown]="true"></p-autoComplete>


export class AutoCompleteDemo {

    text: string;

    results: string[];

    search(event) {
        this.mylookupservice.getResults(event.query).then(data => {
            this.results = data;
        });
    }

    handleDropdown(event) {
        //event.query = current value in input field
    }

}

Multiple Selection

Multiple mode is used to select more than one value from the autocomplete. In this case, model reference should be an array.


<p-autoComplete [(ngModel)]="texts" [suggestions]="results" (completeMethod)="search($event)" [multiple]="true"></p-autoComplete>


export class AutoCompleteDemo {

    texts: string[];

    results: string[];

    search(event) {
        this.mylookupservice.getResults(event.query).then(data => {
            this.results = data;
        });
    }

}

Objects

AutoComplete can also work with objects using the field property that defines the label to display as a suggestion. The value passed to the model would still be the object instance of a suggestion. Here is an example with a Country object that has name and code fields such as {name:"United States",code:"USA"}.


<p-autoComplete [(ngModel)]="val" [suggestions]="results" (completeMethod)="search($event)" field="name"></p-autoComplete>


export class AutoCompleteDemo {

    val: country;

    results: country[];

    search(event) {
        this.countrylookupservice.getResults(event.query).then(data => {
            this.results = data;
        });
    }

}

Force Selection

ForceSelection mode validates the manual input to check whether it also exists in the suggestions list, if not the input value is cleared to make sure the value passed to the model is always one of the suggestions.

            
<p-autoComplete [(ngModel)]="val" [suggestions]="results" (completeMethod)="search($event)" [forceSelection]="true"></p-autoComplete>
            
            

Templating

Item ng-template allows displaying custom content inside the suggestions panel. The local ng-template variable passed to the ng-template is an object in the suggestions array.


<p-autoComplete [(ngModel)]="brand" [suggestions]="filteredBrands" (completeMethod)="filterBrands($event)">
    <ng-template let-brand pTemplate="item">
        <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">
            <img src="assets/showcase/images/demo/car/{{brand}}.png" style="width:32px;display:inline-block;margin:5px 0 2px 5px"/>
            <div style="font-size:18px;float:right;margin:10px 10px 0 0">{{brand}}</div>
        </div>
    </ng-template>
</p-autoComplete>

In multiple mode, selected item can be customized using selectedItem ng-template. Note that this template is not supported in single mode.


<p-autoComplete [(ngModel)]="texts" [suggestions]="results" (completeMethod)="search($event)" [multiple]="true">
    <ng-template let-value pTemplate="selectedItem">
        <span style="font-size:18px">>{{value}}<</span>
    </ng-template>
</p-autoComplete>

Properties

Name Type Default Description
suggestions array null An array of suggestions to display.
field any null Field of a suggested object to resolve and display.
scrollHeight string 200px Maximum height of the suggestions panel.
dropdown boolean false Displays a button next to the input field when enabled.
multiple boolean false Specifies if multiple values can be selected.
minLength number 1 Minimum number of characters to initiate a search.
delay number 300 Delay between keystrokes to wait before sending a query.
style string null Inline style of the component.
styleClass string null Style class of the component.
inputStyle string null Inline style of the input field.
inputStyleClass string null Inline style of the input field.
inputId string null Identifier of the focus input to match a label defined for the component.
placeholder string null Hint text for the input field.
readonly boolean false When present, it specifies that the input cannot be typed.
disabled boolean false When present, it specifies that the component should be disabled.
maxlength number null Maximum number of character allows in the input field.
size number null Size of the input field.
appendTo any null Target element to attach the overlay, valid values are "body" or a local ng-template variable of another element.
tabindex number null Index of the element in tabbing order.
dataKey string null A property to uniquely identify a value in options.
autoHighlight boolean false When enabled, highlights the first item in the list by default.
type string text Type of the input, defaults to "text".
emptyMessage string null Message to display when there are no results for a query.
immutable boolean true Defines how the suggestions should be manipulated. More information is available at "Change Detection" section above.
required boolean false When present, it specifies that an input field must be filled out before submitting the form.
forceSelection boolean false When present, autocomplete clears the manual input if it does not match of the suggestions to force only accepting values from the suggestions.
dropdownMode string blank Specifies the behavior dropdown button. Default "blank" mode sends an empty string and "current" mode sends the input value.

Events

Name Parameters Description
completeMethod event.originalEvent: browser event
event.query: Value to search with
Callback to invoke to search for suggestions.
onFocus event: Browser event Callback to invoke when autocomplete gets focus.
onBlur event: Browser event Callback to invoke when autocomplete loses focus.
onKeyUp event: Browser event Callback to invoke when a user releases a key.
onSelect value: Selected value Callback to invoke when a suggestion is selected.
onUnselect value: Unselected value in multiple mode Callback to invoke when a selected value is removed.
onDropdownClick event.originalEvent: browser event
event.query: Current value of the input field
Callback to invoke to when dropdown button is clicked.
onClear event: browser event Callback to invoke to when inpu field is cleared.

Styling

Following is the list of structural style classes, for theming classes visit theming page.

Name Element
ui-autocomplete Container element
ui-autocomplete-panel Overlay panel of suggestions.
ui-autocomplete-items List container of suggestions.
ui-autocomplete-list-item List item of a suggestion.
ui-autocomplete-token Element of a selected item in multiple mode.
ui-autocomplete-token-icon Close icon element of a selected item in multiple mode.
ui-autocomplete-token-label Label of a selected item in multiple mode.
ui-autocomplete-loader Loader icon.

Dependencies

None.

View on GitHub

<h3 class="first">Basic</h3>
<p-autoComplete [(ngModel)]="country" [suggestions]="filteredCountriesSingle" (completeMethod)="filterCountrySingle($event)" field="name" [size]="30"
    placeholder="Countries" [minLength]="1"></p-autoComplete>
<span style="margin-left:10px">Country: {{country ? country.name||country : 'none'}}</span>

<h3>Advanced</h3>
<p-autoComplete [(ngModel)]="brand" [suggestions]="filteredBrands" (completeMethod)="filterBrands($event)" [size]="30"
    [minLength]="1" placeholder="Hint: type 'v' or 'f'" [dropdown]="true">
    <ng-template let-brand pTemplate="item">
        <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">
            <img src="assets/showcase/images/demo/car/{{brand}}.png" style="width:32px;display:inline-block;margin:5px 0 2px 5px"/>
            <div style="font-size:18px;float:right;margin:10px 10px 0 0">{{brand}}</div>
        </div>
    </ng-template>
</p-autoComplete>
<span style="margin-left:50px">Brand: {{brand||'none'}}</span>

<h3>Multiple</h3>
<span class="ui-fluid">
    <p-autoComplete [(ngModel)]="countries" [suggestions]="filteredCountriesMultiple" (completeMethod)="filterCountryMultiple($event)" styleClass="wid100"
        [minLength]="1" placeholder="Countries" field="name" [multiple]="true">
    </p-autoComplete>
</span>
<ul>
    <li *ngFor="let c of countries">{{c.name}}</li>
</ul>


export class AutoCompleteDemo {

    country: any;

    countries: any[];

    filteredCountriesSingle: any[];

    filteredCountriesMultiple: any[];

    brands: string[] = ['Audi','BMW','Fiat','Ford','Honda','Jaguar','Mercedes','Renault','Volvo','VW'];

    filteredBrands: any[];

    brand: string;

    constructor(private countryService: CountryService) { }

    filterCountrySingle(event) {
        let query = event.query;
        this.countryService.getCountries().then(countries => {
            this.filteredCountriesSingle = this.filterCountry(query, countries);
        });
    }

    filterCountryMultiple(event) {
        let query = event.query;
        this.countryService.getCountries().then(countries => {
            this.filteredCountriesMultiple = this.filterCountry(query, countries);
        });
    }

    filterCountry(query, countries: any[]):any[] {
        //in a real application, make a request to a remote url with the query and return filtered results, for demo we filter at client side
        let filtered : any[] = [];
        for(let i = 0; i < countries.length; i++) {
            let country = countries[i];
            if(country.name.toLowerCase().indexOf(query.toLowerCase()) == 0) {
                filtered.push(country);
            }
        }
        return filtered;
    }

    filterBrands(event) {
        this.filteredBrands = [];
        for(let i = 0; i < this.brands.length; i++) {
            let brand = this.brands[i];
            if(brand.toLowerCase().indexOf(event.query.toLowerCase()) == 0) {
                this.filteredBrands.push(brand);
            }
        }
    }
}


@Injectable()
export class CountryService {

    constructor(private http: Http) {}

    getCountries() {
        return this.http.get('showcase/resources/data/countries.json')
                    .toPromise()
                    .then(res => <any[]> res.json().data)
                    .then(data => { return data; });
    }
}