Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • AngularJS Tutorial
  • AngularJS Directives
  • AngularJS Functions
  • AngularJS Filters
  • AngularJS Examples
  • AngularJS Interview Questions
  • Angular ngx Bootstrap
  • AngularJS Cheat Sheet
  • AngularJS PrimeNG
  • JavaScript
  • Web Technology
Open In App
Next Article:
Angular PrimeNG Calendar Component
Next article icon

Angular PrimeNG Form AutoComplete Component

Last Updated : 21 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that helps to create an attractive user interface with enhanced functionality. These components can be utilized for great styling & are used to make responsive websites with very much ease. There are different functionalities that are supported by the different components, such as the Ripple effect. It is an animation that is supported by the Button Component, which is optional & by default it is disabled & it can be enabled globally in the main component by injecting PrimeNGConfig. The animation is mainly utilized to enhance the overall user experience with the various components.

The PrimeNG facilitates the various components, panels, overlays, menus, charts, etc, which helps to make a single-page-application, that is a web application, that loads a single HTML page and only a part of the page instead of the entire page gets updated with every click of the mouse. This improves the overall user experience, along with adding different functions to perform the specific task, based on the used components.

AutoComplete: In this article, we will know an overview, of Form AutoComponent, along with an understanding of its implementation through the examples.

 

Syntax:

<p-autoComplete></p-autoComplete>

Variations of AutoComplete are:

  • Basic: This is the basic autocomplete component in which you type some words and suggestions will appear in the option.
  • Dropdown and Templating: In this type of variation option will appear when you type or when you click the dropdown icon.
  • Grouped: In this type of variation, the option will appear in the group.
  • Virtual Scroll (10000 Items): In this type of variation you can scroll through the options.
  • Multiple: In this type of variation you can select multiple options.

Properties Used:

  • suggestions: This property is used to define an array of suggestions to display.
  • field: This property is used to define the field of a suggested object to resolve and display.
  • scrollHeight: This property is used to define the maximum height of the suggestions panel.
  • dropdown: This property is used to define the display button next to the input field when enabled.
  • multiple: This property is used to specify if multiple values can be selected.
  • dropdownIcon: This property is used to define the icon class of the dropdown icon.
  • minLength: This property is used to define the minimum number of characters to initiate a search.
  • delay: This property is used to define the delay between keystrokes to wait before sending a query.
  • completeOnFocus: This property is used to run a query when input receives focus.
  • style: This property is used to define the inline style of the component.
  • inputStyle: This property is used to define the inline style of the input field
  • panelStyle: This property is used to define the inline style of the overlay panel element.
  • styleClass:  This property is used to style the class of the component.
  • inputStyleClass: This property is used to define the inline style of the input field.
  • panelStyleClass: This property is used to style the class of the overlay panel element.
  • inputId: This property is used to define the Identifier of the focus input to match a label defined for the component.
  • name: This property is used to define the name of the input element.
  • optionGroupLabel: This property is used to define the name of the label field of an option group.
  • group: This property is used to display options as grouped when nested options are provided.
  • optionGroupChildren: This property is used to define the name of the options field of an option group.
  • placeholder: This property is used to define the hint text for the input field.
  • readonly: This property specifies the input cannot be typed.
  • disabled: This property that the component should be disabled.
  • maxlength: This property is used to define the maximum number of characters allowed in the input field.
  • size: This property is used to define the size of the input field.
  • appendTo: This property is used to define the target element to attach the overlay, valid values are “body” or a local ng-template variable of another element.
  • tabindex: This property is used to define the index of the element in tabbing order.
  • dataKey: This property is used to define the property to uniquely identify a value in options.
  • autoHighlight: This property is used to highlight the first item in the list by default.
  • type: This property is used to define the type of the input, and defaults to “text”.
  • showEmptyMessage: This property is used to show the empty message if true.
  • emptyMessage: This property is used to define the text to display when there is no data.
  • immutable: This property is used to define how the suggestions should be manipulated.
  • required: This property is used to specify that an input field must be filled out before submitting the form.
  • autofocus: This property is used to define the specifications that the component should automatically get focused on load.
  • forceSelection: When this property is present then autocomplete clears the manual input if it does not match the suggestions to force only accepting values from the suggestions.
  • dropdownMode: This property is used to specify the behavior dropdown button.
  • baseZIndex: This property is used to define the base zIndex value to use in layering.
  • autoZIndex: This property is used to define the manage layering automatically.
  • showTransitionOptions: This property is used to define the transition options of the show animation.
  • hideTransitionOptions: This property is used to define the transition options of the hide animation.
  • ariaLabel: This property is used to define the string that labels the input for accessibility.
  • ariaLabelledBy: This property is used to define one or more IDs in the DOM that labels the input field.
  • dropdownAriaLabel: This property is used to define the string that labels the dropdown button for accessibility.
  • unique: This property is used to define the uniqueness of selected items on multiple modes.
  • autocomplete: This property is used to define the string that autocompletes attributes to the current element.
  • showClear: When this property is enabled then a clear icon is displayed to clear the value.
  • virtualScroll: In this property, data should be loaded on demand during the scroll.
  • virtualScrollItemSize: This property is used to define the height of an item in the list for VirtualScrolling.
  • virtualScrollOptions: This property is used for the use of the scroller feature.
  • lazy: This property is used to define if the data is loaded and interacted with in a lazy manner.

Events Used:

  • completeMethod: This template is used to invoke to search for suggestions.
  • onFocus: This template is used to invoke when autocomplete gets focus.
  • onBlur: This template is used to invoke when autocomplete loses focus.
  • onKeyUp: This template is used to invoke when a user releases a key.
  • onSelect: This template is used to invoke when a suggestion is selected.
  • onUnselect: This template is used to invoke when a selected value is removed.
  • onDropdownClick: This template is used to invoke when the dropdown button is clicked.
  • onClear: This template is used to invoke when the input field is cleared.
  • onShow: This template is used to invoke when autocomplete overlay gets visible.
  • onHide: This template is used to invoke when autocomplete overlay gets hidden.
  • onLazyLoad: This template is used to invoke lazy mode to load new data.

Templates Used:

  • item: This template is used to define the data and index of the option.
  • group: This template is used to define the group of the option.
  • selectedItem: This template is used to define the selection of the option.
  • header: This template is used to define the header.
  • footer: This template is used to define the footer.
  • loader: This template is used to define the loader.

Styling Used:

  • p-autocomplete: This is used for the Container element
  • p-autocomplete-panel: This is used for the Overlay panel of suggestions.
  • p-autocomplete-items: This is used for the List container of suggestions.
  • p-autocomplete-item: This is used for the List item of a suggestion.
  • p-autocomplete-token: This is used for the Element of a selected item in multiple mode.
  • p-autocomplete-token-icon: This is used for the Close icon element of a selected item in multiple mode.
  • p-autocomplete-token-label: This is used for the Label of a selected item in multiple modes.
  • p-autocomplete-loader: This is used for the Loader icon.

Steps for creating the Angular PrimeNG Application:

Step 1: Create an Angular application using the following command.

ng new appname

Step 2: After creating your project folder i.e. appname, move to the current working directory where the new app just has been created, by using the following command:

cd appname

Step 3: Install PrimeNG in your given directory.

npm install primeng --save  npm install primeicons --save

Project Structure: After successful installation, it will look like the following image:

 

Example 1: In the below code, we will see how the Form AutoComplete component works.

app.component.html

HTML

<!DOCTYPE html>
<html>
  
<head>
    <title>GFG</title>
    <style>
        body {
            background-color: lightgrey;
            text-align: center;
        }
  
        p-autoComplete {
            border: 16px solid green;
        }
    </style>
</head>
  
<body>
    <div>
        <h1 style="color: green">GeeksforGeeks</h1>
        <h3>A computer science portal for geeks</h3>
        <h2>Form AutoComplete</h2>
        <h5>Basic</h5>
        <p-autoComplete [(ngModel)]="selectedCountry"
                        [suggestions]="filteredCountries"
                        (completeMethod)="filterCountry($event)" 
                        field="name" [minLength]="1">
        </p-autoComplete>
    </div>
</body>
  
</html>
                      
                       

app.component.ts

Javascript

import { Component } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { SelectItem } from 'primeng/api';
import { SelectItemGroup } from 'primeng/api';
import { FilterService } from 'primeng/api';
import { CountryService } from './countryservice';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    providers: [CountryService, FilterService],
})
export class AppComponent {
    selectedCountry: any;
  
    countries: any[];
  
    filteredCountries: any[];
  
    selectedCountries: any[];
  
    selectedCountryAdvanced: any[];
  
    filteredBrands: any[];
  
    groupedCities: SelectItemGroup[];
  
    filteredGroups: any[];
  
    constructor(
        private countryService: CountryService,
        private filterService: FilterService
    ) { }
  
    ngOnInit() {
        this.countryService.getCountries().then((countries) => {
            this.countries = countries;
        });
  
        this.groupedCities = [
            {
                label: 'India',
                value: 'IND',
                items: [
                    { label: 'Mumbai', value: 'Berlin' },
                    { label: 'Goa', value: 'Frankfurt' },
                    { label: 'Varanasi', value: 'Hamburg' },
                    { label: 'Dadar', value: 'Munich' },
                ],
            },
        ];
    }
  
    filterCountry(event) {
        let filtered: any[] = [];
        let query = event.query;
        for (let i = 0; i < this.countries.length; i++) {
            let country = this.countries[i];
            if (country.name.toLowerCase().indexOf(query.toLowerCase()) == 0) {
                filtered.push(country);
            }
        }
  
        this.filteredCountries = filtered;
    }
  
    filterGroupedCity(event) {
        let query = event.query;
        let filteredGroups = [];
  
        for (let optgroup of this.groupedCities) {
            let filteredSubOptions = this.filterService.filter(
                optgroup.items,
                ['label'],
                query,
                'contains'
            );
            if (filteredSubOptions && filteredSubOptions.length) {
                filteredGroups.push({
                    label: optgroup.label,
                    value: optgroup.value,
                    items: filteredSubOptions,
                });
            }
        }
  
        this.filteredGroups = filteredGroups;
    }
}
                      
                       

countryservice.ts

Javascript

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
  
@Injectable()
export class CountryService {
    constructor(private http: HttpClient) { }
  
    getCountries() {
        return this.http
            .get < any > ('assets/countries.json')
                .toPromise()
                .then((res) => <any[] > res.data)
                .then((data) => {
                    return data;
                });
    }
}
                      
                       

countries.json

Javascript

{
    "data": [ 
        {"name": "Hungary", "code": "HU"}, 
        {"name": "Iceland", "code": "IS"}, 
        {"name": "India", "code": "IN"}, 
        {"name": "Indonesia", "code": "ID"}, 
        {"name": "Iran, Islamic Republic Of", "code": "IR"}, 
        {"name": "Iraq", "code": "IQ"}, 
        {"name": "Ireland", "code": "IE"}, 
        {"name": "Isle of Man", "code": "IM"}, 
        {"name": "Israel", "code": "IL"}, 
        {"name": "Italy", "code": "IT"}, 
        {"name": "Jamaica", "code": "JM"}, 
        {"name": "Japan", "code": "JP"}, 
        
    ]
}
                      
                       

Output:

 

Example 2: In the below code, we will make use of the above syntax to demonstrate the use of Form AutoComplete Component

app.component.html

HTML

<!DOCTYPE html>
<html>
  
<head>
    <title>GFG</title>
    <style>
        body {
            background-color: lightgrey;
            text-align: center;
            width: 550px;
            height: 550px
        }
  
        p-autoComplete {
            border: 16px solid green;
        }
    </style>
</head>
  
<body>
    <div style="text-align:center;">
        <h1 style="color:green;">GeeksforGeeks</h1>
        <h3>A computer science portal for geeks</h3>
        <h4>Angular PrimeNG Form AutoComplete Component</h4>
        <h5>Dropdown</h5>
        <p-autoComplete [(ngModel)]="selectedCountryAdvanced"
                        [suggestions]="filteredCountries"
                         (completeMethod)="filterCountry($event)"
                        field="name" [dropdown]="true">
            <ng-template let-country pTemplate="item">
                <div class="country-item">
                    <div>{{ country.name }}</div>
                </div>
            </ng-template>
        </p-autoComplete>
    </div>
</body>
  
</html>
                      
                       

app.component.ts

Javascript

import { Component } from "@angular/core";
import { MenuItem } from "primeng/api";
import { SelectItem } from "primeng/api";
import { SelectItemGroup } from "primeng/api";
import { FilterService } from "primeng/api";
import { CountryService } from "./countryservice";
  
@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    providers: [CountryService, FilterService]
})
export class AppComponent {
    selectedCountry: any;
  
    countries: any[];
  
    filteredCountries: any[];
  
    selectedCountries: any[];
  
    selectedCountryAdvanced: any[];
  
    filteredBrands: any[];
  
    groupedCities: SelectItemGroup[];
  
    filteredGroups: any[];
  
    constructor(
        private countryService: CountryService,
        private filterService: FilterService
    ) { }
  
    ngOnInit() {
        this.countryService.getCountries().then(countries => {
            this.countries = countries;
        });
  
        this.groupedCities = [
            {
                label: "India",
                value: "IND",
                items: [
                    { label: "Mumbai", value: "Berlin" },
                    { label: "Goa", value: "Frankfurt" },
                    { label: "Varanasi", value: "Hamburg" },
                    { label: "Dadar", value: "Munich" }
                ]
            },
        ];
    }
  
    filterCountry(event) {
  
        let filtered: any[] = [];
        let query = event.query;
        for (let i = 0; i < this.countries.length; i++) {
            let country = this.countries[i];
            if (country.name.toLowerCase().indexOf(query.toLowerCase()) == 0) {
                filtered.push(country);
            }
        }
  
        this.filteredCountries = filtered;
    }
  
    filterGroupedCity(event) {
        let query = event.query;
        let filteredGroups = [];
  
        for (let optgroup of this.groupedCities) {
            let filteredSubOptions = this.filterService.filter(
                optgroup.items,
                ["label"],
                query,
                "contains"
            );
            if (filteredSubOptions && filteredSubOptions.length) {
                filteredGroups.push({
                    label: optgroup.label,
                    value: optgroup.value,
                    items: filteredSubOptions
                });
            }
        }
  
        this.filteredGroups = filteredGroups;
    }
}
                      
                       

app.module.ts

Javascript

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from
    '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
  
import { AppComponent } from './app.component';
  
import { AutoCompleteModule } from 'primeng/autocomplete';
  
@NgModule({
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        AutoCompleteModule,
        FormsModule,
        HttpClientModule,
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
})
export class AppModule { }
                      
                       

countryservice.ts

Javascript

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
  
@Injectable()
export class CountryService {
    constructor(private http: HttpClient) { }
  
    getCountries() {
        return this.http
            .get < any > ('assets/countries.json')
                .toPromise()
                .then((res) => <any[] > res.data)
                .then((data) => {
                    return data;
                });
    }
}
                      
                       

countries.json

Javascript

{
    "data": [
        { "name": "Iceland", "code": "IS" },
        { "name": "India", "code": "IN" },
        { "name": "Indonesia", "code": "ID" },
        { "name": "Iran, Islamic Republic Of", "code": "IR" },
        { "name": "Iraq", "code": "IQ" },
        { "name": "Ireland", "code": "IE" },
        { "name": "Isle of Man", "code": "IM" },
        { "name": "Israel", "code": "IL" },
        { "name": "Italy", "code": "IT" }
    ]
}
                      
                       

Output:

 



Next Article
Angular PrimeNG Calendar Component
author
krishna_97
Improve
Article Tags :
  • AngularJS
  • Web Technologies
  • Angular-PrimeNG
  • PrimeNG-Form

Similar Reads

  • Angular PrimeNG Form AutoComplete Component
    Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that helps to create an attractive user interface with enhanced functionality. These components can be utilized for great styling & are used to make responsive websites with very much ease. There are diff
    12 min read
  • Angular PrimeNG Calendar Component
    Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the calendar component in angular ngx bootstrap. Calendar c
    8 min read
  • Angular PrimeNG Form CascadeSelect Component
    Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use the Angular PrimeNG Form CascadeSelect Component. The CascadeSe
    6 min read
  • Angular PrimeNG Form Checkbox Component
    Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. This article will show us how to use the calendar component in angular ngx bootstrap. Checkbox Compo
    5 min read
  • Angular PrimeNG Chips Component
    Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Chips component in Angular PrimeNG. Chips component: It
    5 min read
  • Angular PrimeNG ColorPicker Component
    Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the colorPicker component in Angular PrimeNG. colorPicker c
    5 min read
  • Angular PrimeNG Dropdown Component
    Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Dropdown component in Angular ngx Bootstrap. We will al
    9 min read
  • Angular PrimeNG Form Editor Component
    Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the Form Editor Component in Angular PrimeNG. The Form Edito
    3 min read
  • Angular PrimeNG FloatLabel Component
    Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the FloatLabel component in angular PrimeNG. FloatLabel com
    2 min read
  • Angular PrimeNG InputGroup Component
    Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the InputGroup component in angular primeNG. InputGroup com
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences