Wednesday, September 19, 2018

Primeng Autocomplete Angular tutorial with examples

In this blog post, We are going to learn Implement Autocomplete feature of Primeng in Angular with an example.

Angular Autocomplete Component 

Autocomplete is a User interface feature and it contains an Input text box and allows the developer to type text, and application display the matched words results for typed characters and give complete word prediction list. It is an easy way to select the text from the user text box. This is a basic UI element on every UI framework provides. Primeng also provides as an angular component.

Angular Application Example

First, create an angular application using Angular CLI. You can check my previous post of Angular application generation from scratch and also about Primeng Integration example of Angular. This article does not talk about the angular application structure and primeng integration. Please find below other tutorials of Primeng.
This article code works on angular 4/5/6 versions. The latest Angular version is preferable for Primeng framework.

Import AutoCompleteModule module

Primeng provides autocomplete feature AutoCompleteModule. So you have to import this module in your application module. In-app module file, Import autocomplete module and configure Imports section of NgModule configuration
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations'; 
import {AutoCompleteModule} from 'primeng/autocomplete';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AutoCompleteModule, // autocomplete support
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas:
        [CUSTOM_ELEMENTS_SCHEMA]

})
export class AppModule { }

Application Component Configuration -app.component.ts  

In Application Component, Need to provide data as well as method or function that checks against typed keyword
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  numbers: string[] = ['onne','two','three','four','five','six','seven','eight','nine','ten'];
  output: string[];
  constructor(){

  }
  search(event) {
    console.log('event',event);
    this.output = this.numbers.filter(c => c.startsWith(event.query));
}
}

Template HTML Changes - app.component.html

 In the template HTML changes, Configured two-way binding using ngModel attribute And also added suggestions attribute for list of suggestions for typed query CompleteMethod method will be fired when the user typed a key and it has a parameter of the event. query parameters which contain the typed keyword. This method returns the matched query list of content and updates to suggestions binding
<div style="text-align:center">
   <h1>
      Primeng Angular AutoComplete Demo
   </h1>
</div>
<div style="text-align:center">
    <p-autoComplete [(ngModel)]="selectNumber" [suggestions]="output" (completeMethod)="search($event)"
    placeholder="Search" [dropdown]="true" ></p-autoComplete>
</div>
Output
primeng angular autocomplete example

Dropdown Attribute 

By default, This is set to false. It displays a button next to textbox when dropdown=true. You can check output of configuring dropdown property
Angular Primeng Autocomplete dropdown example

Multiple values select 

Multiple values can be selected by setting multiple properties to true. Two-way binding module also should be a String array instead of a single string. selectNumber: string[]; instead of selectNumber: string;
    <p-autoComplete [(ngModel)]="selectNumber" [suggestions]="output" (completeMethod)="search($event)"
 placeholder="Search" [dropdown]="true" [multiple]="true" ></p-autoComplete>
Please see the output of the above
primeng angular autocomplete multiple values select

Objects and ng-template Example 

As of now, saw an example how simple strings can be populated. We can also populate Object binding using field property In the Object, We have id, name and department fields. The object is matched with name field with typed word. Field defines the label of the object that needs to display. ng-template tag allows the component to display custom content. In this example displaying name and department as the custom template 
app.component.ts
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  employee:any;
  employees = [
    {"id": 1, "name": "kiran", "department": "Account"},
    {"id": 2, "name": "john", "department": "Sales"},
    {"id": 3, "name": "frank", "department": "Hr"},
  ];
  employeesResult: Array = [];  
  constructor(){
  }
  searchEmps(event): void {
    this.employeesResult = this.employees.filter(c => c.name.startsWith(event.query));

 }
}
app.component.html
<div style="text-align:center">
   <h1>
      Primeng Angular AutoComplete Object Demo
   </h1>
</div>
<div style="text-align:center">
    <p-autoComplete [(ngModel)]="employee" [suggestions]="employeesResult" (completeMethod)="searchEmps($event)" field="name">
        <ng-template let-employee pTemplate="item">
          {{employee.name}} {{employee.department}}
        </ng-template>
        <ng-template let-employee pTemplate="selectedItem">
            {{employee.name}} {{employee.department}}
        </ng-template>
      </p-autoComplete>

</div>
You can check the output
angular primeng autocomplete object example

Related article


EmoticonEmoticon