{

Primeng Autocomplete Angular tutorial with examples


Primeng Angular 13 Auto complete example

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

Angular Autocomplete Component

Autocomplete is a User interface feature it contains an Input text box and allows the developer to type text, and the application search and display the matched word results for typed characters and give a complete word prediction list.

This is helpful for the user to search and select instead of typing in the text box.

This is a basic UI element on every UI framework provided.

Primeng provides an angular component.

Create an angular application using CLI

First, create an angular application using Angular CLI.

You can check my previous post on Angular application generation from scratch and also about the Primeng Integration example of Angular.

This article does not talk about the angular application structure and primeng integration.

Please find below other tutorials on Primeng.

This article code works on angular 10/11/12/13 versions.

The latest Angular version is preferable for the Primeng framework.

Import AutoCompleteModule module

Primeng provides autocomplete feature via AutoCompleteModule. So, you have to import this module into your application module. app.module.ts 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 a method or function that checks against a typed keyword.

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  numbers: string[] = ['one,'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 the suggestions attribute for the list of suggestions for the typed query.
  • Complete Method method will be fired when the user typed a key
  • It has a parameter of the event. query parameters that 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

How to add a Dropdown to autocomplete component?

By default, This is set to false. It displays a button next to the textbox if a dropdown changes to true.

You can check the output of configuring the dropdown property

Angular Primeng Autocomplete dropdown example

How to select multiple elements in autocomplete?

Multiple values can be selected by setting multiple properties to true. The two-way binding attribute also should be a string array instead of a single string.

i.e 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

How to bind an object and ng-template Example

We saw the above example of 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 the name field with the typed word.

The field defines the label of the object that needs to display.

the ng-template tag allows the component to display custom content. This example displays the 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

Conclusion

You learned the integration of autocomplete component integration in the Angular component and learned a few features.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Angular 13 Lowercase pipe tutorial | How to Convert a string to small case example

Angular 13 Sweetalert tutorial|popup notification in Angular example

Angular 13 Titlecase pipe tutorial | How to Capitalize the first letter of each word of a string example

Angular 13 UpperCase pipe tutorial | How to Convert a String to Uppercase example

Angular LocalStorage, SessionStorage example | Ngx-webstorage tutorial

Angular primeng bar chart|p-chart bar type example

Angular Semantic UI Popup Modal | ng2-semantic-ui example