Open In App

Angular PrimeNG Form AutoComplete Component

Improve
Improve
Like Article
Like
Save
Share
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:

 

Reference: https://www.primefaces.org/primeng/autocomplete



Last Updated : 16 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads