Angular

Country List AutoComplete Using PrimeNG In Angular

Introduction

In this article, we will learn about how to add autocomplete with country list and icon in Angular using PrimeNg and Bootstrap 4.

Prerequisites

  • Angular CLI
  • TypeScript
  • Visual Studio Code
  • JSON Data
  • Dependency injection

Description

Here, I will show you the steps to add autocomplete country list and icon using JSON data and service.

Note

Before going through this session, please check my previous article related to Add Country Flags.

What Is PrimeNg?

PrimeNG is a rich set of open-source native Angular UI components. The Ultimate UI Component Library for Angular. You can easily implement it on the angular site. If you want you can take a look at official site of PrimeNG

Lets start with it.

We will be using json file for getting the data of countries, you can download it from my github account from here.

CountryList.Json

In Autocomplete Component folder add DTO file Country-modal.ts

export interface ICountry{
    code : string,
    code3 : string,
    name : string,
    number : string
}
I have created on function in the service to get data of autocomplete, have look of data-list.service.ts
import { HttpClient } from '@angular/common/http';
import { ICountry } from './county/CountryLIst';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataListService {

  private _url: string = '/assets/CountyList.json';
  
  constructor(private http: HttpClient) {}

  getCountries() : Observable<ICountry[]> {
    return this.http.get<ICountry[]>(this._url);
  }
}
Now, let’s call service function on page ready, have a look of autocomplete.component.ts
import { DataListService } from './../data-list.service';
import { Component, OnInit } from '@angular/core';
import {AutoCompleteModule} from 'primeng/autocomplete';


@Component({
  selector: 'app-autocomplete',
  templateUrl: './autocomplete.component.html',
  styleUrls: ['./autocomplete.component.css']
})
export class AutocompleteComponent implements OnInit {


    public con = [];
    countries: any[];
    selectedCountry="";     
    filteredCountries: any[];
    selectedCountries: any[];
    selectedCountryAdvanced: any[];


  constructor(private _service : DataListService) { }


  ngOnInit(): void {
    this._service.getCountries().subscribe(countries => {
      this.countries = countries});
  }


  filterCountry(event) {
  //in a real application, make a request to a remote url with the query and return filtered results, for demo we filter at client side
    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;
  }
}

 

here is my html structure to manage autocomplete, have a look of autocomplete.component.html
<div class="container">
  <h1 class="text-info">./autocomplete</h1>
  <h2 class="text-warning">//Using Prime NG</h2>
  <div class="row">
    <div class="col-md-1">
      <h4 class="text-dark" style="padding-top: 5px">Country</h4>
    </div>
    <div class="col-md-4">
      <p-autoComplete
        [(ngModel)]="selectedCountry"
        [suggestions]="filteredCountries"
        (completeMethod)="filterCountry($event)"
        field="name"
        [minLength]="1"
        placeholder="Enter a Country Name"
      ></p-autoComplete>
    </div>
  </div>
  <hr />
  <div class="row">
    <div class="col-md-4">
      <h4 class="text-dark" style="padding-top: 5px">
        Dropdown and Templating
      </h4>
    </div>
    <div class="col-md-6">
      <p-autoComplete
        [(ngModel)]="selectedCountryAdvanced"
        [suggestions]="filteredCountries"
        (completeMethod)="filterCountry($event)"
        field="name"
        [dropdown]="true"
      >
        <ng-template let-country pTemplate="item">
          <div
            class="country-item"
            style="position: relative; padding-left: 20px"
          >
            <span
              class=" flag flag-icon flag-icon-{{
                country.code | lowercase
              }} flag-icon-squared"
              style="
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
              "
            >
            </span>
            <div>{{ country.name }}</div>
          </div>
        </ng-template>
      </p-autoComplete>
    </div>
  </div>
  <hr />
  <div class="row">
    <div class="col-md-2">
      <h4 class="text-dark" style="padding-top: 5px">Multiple</h4>
    </div>
    <div class="col-md-6">
      <p-autoComplete
        [(ngModel)]="selectedCountries"
        [suggestions]="filteredCountries"
        (completeMethod)="filterCountry($event)"
        field="name"
        [multiple]="true"
      >
        <ng-template let-country pTemplate="item">
          <div
            class="country-item"
            style="position: relative; padding-left: 20px"
          >
            <span
              class=" flag flag-icon flag-icon-{{
                country.code | lowercase
              }} flag-icon-squared"
              style="
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
              "
            >
            </span>
            <div>{{ country.name }}</div>
          </div>
        </ng-template>
      </p-autoComplete>
    </div>
  </div>
</div>

That’s it.

OUTPUT

I hope you guys understand how we can do that.

Let me know if you face any difficulties.

 

Nayan Raval

Nayan Raval is a MEAN Stack .Net Developer has extensive experience with designing and developing enterprise-scale applications. Key Areas Of Expertise: • ASP.NET Core MVC • ASP.NET Core Web API • C# • ASP.NET MVC 5 • Angular All versions • HTML5 • CSS3 / SCSS • Bootstrap • JavaScript • Azure • JQuery Databases and related • Microsoft SQL server MSSQL • PostgreSQL • Entity Framework (EF) • LINQ UI Frameworks • Kendo UI • Telerik • JQuery UI • Prime NG and Material UI API Integration • SignalR • DateDog • Twilio Voice Call And Message • Stripe • SendGrid (Email Camping) • Checkr • Zoom Video Call • Auth0 • Elastic Search • Quartz - Scheduler • JWT Token • Google Calendar

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago