Open In App

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 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:

Properties Used:

Events Used:

Templates Used:

Styling Used:

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




<!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




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




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




{
    "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




<!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




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




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




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




{
    "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


Article Tags :