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

AutoComplete - 图1

Documentation

Import

  1. import {AutoCompleteModule} from 'primeng/autocomplete';
  2.  

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.

  1. <p-autoComplete [(ngModel)]="text" [suggestions]="results" (completeMethod)="search($event)"></p-autoComplete>
  2.  
  1. export class AutoCompleteDemo {
  2. text: string;
  3. results: string[];
  4. search(event) {
  5. this.mylookupservice.getResults(event.query).then(data => {
  6. this.results = data;
  7. });
  8. }
  9. }
  10.  

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.

Note that if no suggestions are available after searching, provide an empty array instead of a null value.

Model Driven Forms

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

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

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.

  1. <p-autoComplete [(ngModel)]="text" [suggestions]="results" (completeMethod)="search($event)"
  2. [dropdown]="true"></p-autoComplete>
  3.  
  1. export class AutoCompleteDemo {
  2. text: string;
  3. results: string[];
  4. search(event) {
  5. this.mylookupservice.getResults(event.query).then(data => {
  6. this.results = data;
  7. });
  8. }
  9. handleDropdown(event) {
  10. //event.query = current value in input field
  11. }
  12. }
  13.  

Multiple Selection

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

  1. <p-autoComplete [(ngModel)]="texts" [suggestions]="results" (completeMethod)="search($event)" [multiple]="true"></p-autoComplete>
  2.  
  1. export class AutoCompleteDemo {
  2. texts: string[];
  3. results: string[];
  4. search(event) {
  5. this.mylookupservice.getResults(event.query).then(data => {
  6. this.results = data;
  7. });
  8. }
  9. }
  10.  

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"}.

  1. <p-autoComplete [(ngModel)]="val" [suggestions]="results" (completeMethod)="search($event)" field="name"></p-autoComplete>
  2.  
  1. export class AutoCompleteDemo {
  2. val: country;
  3. results: country[];
  4. search(event) {
  5. this.countrylookupservice.getResults(event.query).then(data => {
  6. this.results = data;
  7. });
  8. }
  9. }
  10.  

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.

  1. <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.

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

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

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

Animation Configuration

Transition of the open and hide animations can be customized using the showTransitionOptions and hideTransitionOptions properties, example below disables the animations altogether.

  1. <p-autoComplete [showTransitionOptions]="'0ms'" [hideTransitionOptions]="'0ms'" [(ngModel)]="texts" [suggestions]="results" (completeMethod)="search($event)"></p-autoComplete>
  2.  

Properties

NameTypeDefaultDescription
suggestionsarraynullAn array of suggestions to display.
fieldanynullField of a suggested object to resolve and display.
scrollHeightstring200pxMaximum height of the suggestions panel.
dropdownbooleanfalseDisplays a button next to the input field when enabled.
multiplebooleanfalseSpecifies if multiple values can be selected.
dropdownIconstringpi pi-caret-downIcon class of the dropdown icon.
minLengthnumber1Minimum number of characters to initiate a search.
delaynumber300Delay between keystrokes to wait before sending a query.
stylestringnullInline style of the component.
styleClassstringnullStyle class of the component.
inputStylestringnullInline style of the input field.
inputStyleClassstringnullInline style of the input field.
inputIdstringnullIdentifier of the focus input to match a label defined for the component.
placeholderstringnullHint text for the input field.
readonlybooleanfalseWhen present, it specifies that the input cannot be typed.
disabledbooleanfalseWhen present, it specifies that the component should be disabled.
maxlengthnumbernullMaximum number of character allows in the input field.
sizenumbernullSize of the input field.
appendToanynullTarget element to attach the overlay, valid values are "body" or a local ng-template variable of another element.
tabindexnumbernullIndex of the element in tabbing order.
dataKeystringnullA property to uniquely identify a value in options.
autoHighlightbooleanfalseWhen enabled, highlights the first item in the list by default.
typestringtextType of the input, defaults to "text".
emptyMessagestringnullMessage to display when there are no results for a query.
immutablebooleantrueDefines how the suggestions should be manipulated. More information is available at "Change Detection" section above.
requiredbooleanfalseWhen present, it specifies that an input field must be filled out before submitting the form.
autofocusbooleanfalseWhen present, it specifies that the component should automatically get focus on load.
forceSelectionbooleanfalseWhen present, autocomplete clears the manual input if it does not match of the suggestions to force only accepting values from the suggestions.
dropdownModestringblankSpecifies the behavior dropdown button. Default "blank" mode sends an empty string and "current" mode sends the input value.
baseZIndexnumber0Base zIndex value to use in layering.
autoZIndexbooleantrueWhether to automatically manage layering.
showTransitionOptionsstring225ms ease-outTransition options of the show animation.
hideTransitionOptionsstring195ms ease-inTransition options of the hide animation.
ariaLabelstringnullDefine a string that labels the input field.
ariaLabelledBystringnullSpecifies one or more IDs in the DOM that labels the input field.

Events

NameParametersDescription
completeMethod event.originalEvent: browser event event.query: Value to search with Callback to invoke to search for suggestions.
onFocusevent: Browser eventCallback to invoke when autocomplete gets focus.
onBlurevent: Browser eventCallback to invoke when autocomplete loses focus.
onKeyUpevent: Browser eventCallback 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 when dropdown button is clicked.
onClearevent: browser eventCallback to invoke when input field is cleared.

Styling

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

NameElement
ui-autocompleteContainer element
ui-autocomplete-panelOverlay panel of suggestions.
ui-autocomplete-itemsList container of suggestions.
ui-autocomplete-list-itemList item of a suggestion.
ui-autocomplete-tokenElement of a selected item in multiple mode.
ui-autocomplete-token-iconClose icon element of a selected item in multiple mode.
ui-autocomplete-token-labelLabel of a selected item in multiple mode.
ui-autocomplete-loaderLoader icon.

Dependencies

None.

Source

View on GitHub

  1. <h3 class="first">Basic</h3>
  2. <p-autoComplete [(ngModel)]="country" [suggestions]="filteredCountriesSingle" (completeMethod)="filterCountrySingle($event)" field="name" [size]="30"
  3. placeholder="Countries" [minLength]="1"></p-autoComplete>
  4. <span style="margin-left:10px">Country: {{country ? country.name||country : 'none'}}</span>
  5. <h3>Advanced</h3>
  6. <p-autoComplete [(ngModel)]="brand" [suggestions]="filteredBrands" (completeMethod)="filterBrands($event)" [size]="30"
  7. [minLength]="1" placeholder="Hint: type 'v' or 'f'" [dropdown]="true">
  8. <ng-template let-brand pTemplate="item">
  9. <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">
  10. <img src="assets/showcase/images/demo/car/{{brand}}.png" style="width:32px;display:inline-block;margin:5px 0 2px 5px"/>
  11. <div style="font-size:18px;float:right;margin:10px 10px 0 0">{{brand}}</div>
  12. </div>
  13. </ng-template>
  14. </p-autoComplete>
  15. <span style="margin-left:50px">Brand: {{brand||'none'}}</span>
  16. <h3>Multiple</h3>
  17. <span class="ui-fluid">
  18. <p-autoComplete [(ngModel)]="countries" [suggestions]="filteredCountriesMultiple" (completeMethod)="filterCountryMultiple($event)" styleClass="wid100"
  19. [minLength]="1" placeholder="Countries" field="name" [multiple]="true">
  20. </p-autoComplete>
  21. </span>
  22. <ul>
  23. <li *ngFor="let c of countries">{{c.name}}</li>
  24. </ul>
  25.  
  1. export class AutoCompleteDemo {
  2. country: any;
  3. countries: any[];
  4. filteredCountriesSingle: any[];
  5. filteredCountriesMultiple: any[];
  6. brands: string[] = ['Audi','BMW','Fiat','Ford','Honda','Jaguar','Mercedes','Renault','Volvo','VW'];
  7. filteredBrands: any[];
  8. brand: string;
  9. constructor(private countryService: CountryService) { }
  10. filterCountrySingle(event) {
  11. let query = event.query;
  12. this.countryService.getCountries().then(countries => {
  13. this.filteredCountriesSingle = this.filterCountry(query, countries);
  14. });
  15. }
  16. filterCountryMultiple(event) {
  17. let query = event.query;
  18. this.countryService.getCountries().then(countries => {
  19. this.filteredCountriesMultiple = this.filterCountry(query, countries);
  20. });
  21. }
  22. filterCountry(query, countries: any[]):any[] {
  23. //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
  24. let filtered : any[] = [];
  25. for(let i = 0; i < countries.length; i++) {
  26. let country = countries[i];
  27. if(country.name.toLowerCase().indexOf(query.toLowerCase()) == 0) {
  28. filtered.push(country);
  29. }
  30. }
  31. return filtered;
  32. }
  33. filterBrands(event) {
  34. this.filteredBrands = [];
  35. for(let i = 0; i < this.brands.length; i++) {
  36. let brand = this.brands[i];
  37. if(brand.toLowerCase().indexOf(event.query.toLowerCase()) == 0) {
  38. this.filteredBrands.push(brand);
  39. }
  40. }
  41. }
  42. }
  43.  
  1. @Injectable()
  2. export class CountryService {
  3. constructor(private http: Http) {}
  4. getCountries() {
  5. return this.http.get('showcase/resources/data/countries.json')
  6. .toPromise()
  7. .then(res => <any[]> res.json().data)
  8. .then(data => { return data; });
  9. }
  10. }
  11.