DEV Community

Cover image for 🌍 How to Create a Country Autocomplete in Angular: A Step-by-Step Guide 🌍
wlucha
wlucha

Posted on

🌍 How to Create a Country Autocomplete in Angular: A Step-by-Step Guide 🌍

Empower your Angular apps with an elegant, multilingual country search.

1. Introduction

When building any globally targeted Angular application — be it for e-commerce, social platforms, or travel portals — your users often need to select their country. A country dropdown or autocomplete can be surprisingly tricky to build from scratch: You might need to manage large lists of country names, codes, and even flags for a polished user experience. Not to mention supporting multiple languages and different forms of search (e.g., by ISO code, local name, or English name).

In this guide, we’ll explore a simple yet powerful way to implement a country selection feature in your Angular project. We’ll walk you through the entire process, from setting up a brand-new Angular Material project to integrating a robust, ready-made country selection component using @wlucha/ng-country-select. Let’s dive right in! 🌐

2. Why Use a Pre-Built Country Autocomplete?

Before we jump into coding, let’s talk about why you might want to use a pre-built solution. Managing a high-quality country autocomplete can be challenging for several reasons:

  1. Huge List: There are nearly 200 countries worldwide, each with distinct codes (ISO Alpha2, Alpha3) and localized names.

  2. Multilingual Requirements: Your users may need to see country names in different languages.

  3. Flags: Displaying flags as images or emojis can be tricky to handle efficiently.

  4. Search Complexity: Supporting partial matches, synonyms, or codes can increase your data-management overhead.

A specialized library like @wlucha/ng-country-select handles all these complexities for you — complete with Angular Material design, flags rendered via emojis, multi-language support, and efficient searching powered by RxJS. This means you can focus on your application’s core functionality while ensuring a polished and intuitive user experience. ✨

3. Getting Started

3.1. Create (or Open) Your Angular Project

If you haven’t already set up an Angular project, you can do so in a snap using the Angular CLI:

npm install -g @angular/cli
ng new country-demo
cd country-demo
Enter fullscreen mode Exit fullscreen mode

When prompted, you can choose to include Angular routing and select your preferred stylesheet format. Once done, open the project in your favorite code editor (VS Code, WebStorm, etc.).

3.2. Include Angular Material (Optional but Recommended)

Since @wlucha/ng-country-select is built with Angular Material design in mind, you might want to install and configure Angular Material if you haven’t already:

ng add @angular/material
Enter fullscreen mode Exit fullscreen mode

You will be prompted to choose a Material theme, set up gestures, and enable browser animations. Follow the prompts to complete the installation. This step ensures that your app is styled in line with Material Design guidelines.

4. Install the "@wlucha/ng-country-select" Library

Now, let’s add the country autocomplete library to our project. This single command installs all necessary dependencies:

npm install --save @angular/material @angular/cdk @angular/animations @wlucha/ng-country-select
Enter fullscreen mode Exit fullscreen mode

Note: If you’ve already installed Angular Material (@angular/material, @angular/cdk, and @angular/animations), you only need:

npm install --save @wlucha/ng-country-select
Enter fullscreen mode Exit fullscreen mode

5. Configure the Module

In Angular, we need to import the component that we want to use. Head over to your app.module.ts (or any module where you want to use the country select) and add the CountrySelectComponent:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { CountrySelectComponent } from '@wlucha/ng-country-select';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';@NgModule({
      declarations: [AppComponent],
      imports: [
        BrowserModule,
        BrowserAnimationsModule, // Required for Angular Material animations
        CountrySelectComponent
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

With this, the component is ready to be used in your templates.

6. Basic Usage: A Simple Example

Let’s create a straightforward autocomplete in our app.component.html to see how this works:

<h2>Select Your Country 🌏</h2>
<ng-country-select
   [lang]="'en'"
   (countrySelected)="handleSelection($event)"
></ng-country-select>
Enter fullscreen mode Exit fullscreen mode

Then, in app.component.ts:

import { Component } from '@angular/core';
import { Country } from '@wlucha/ng-country-select';

@Component({
      selector: 'app-root',
      templateUrl: './app.component.html'
})
export class AppComponent {
  handleSelection(selectedCountry: Country): void {
    console.log('Selected country:', selectedCountry);
    // Perform any logic based on the chosen country (e.g., storing user profile info)
      }
    }
Enter fullscreen mode Exit fullscreen mode

Boom — that’s all you need for a functional country autocomplete! ✅ Users can type to filter the list, and once they choose a country, the (countrySelected) event emits the full Country object.

7. Digging Deeper: Key Features & Customization

@wlucha/ng-country-select offers a host of features that make it easy to tailor the country selection experience to your needs:

7.1. Multi-Language Magic

Out of the box, you can switch the language by using the lang input property:

<ng-country-select [lang]="'de'"></ng-country-select>
Enter fullscreen mode Exit fullscreen mode

This will display country names in German. Supported languages include: English (en), German (de), French (fr), Spanish (es), and Italian (it). You can even search for a country in all available translations with:

<ng-country-select
  [searchAllLanguages]="true"
></ng-country-select>
Enter fullscreen mode Exit fullscreen mode

7.2. Smart Search & Flags

Each country is displayed with an emoji flag (no extra images needed!) and is searchable by local name, English name, and ISO codes (Alpha2 or Alpha3). It makes finding a country super easy.

7.3. Angular Material Integration

Because it uses Angular Material’s MatFormField and MatInput, you get consistent styling and theming out of the box. You can choose 'fill' or 'outline' appearances to match your app’s style, e.g.:

<ng-country-select [appearance]="'outline'"></ng-country-select>
Enter fullscreen mode Exit fullscreen mode

7.4. Performance Optimizations

The library comes with debounce search input to reduce unnecessary lookups. You can configure the delay:

<ng-country-select [debounceTime]="300"></ng-country-select>
Enter fullscreen mode Exit fullscreen mode

This ensures that searches are not fired on every keystroke but only after the user stops typing for 300 ms.

8. Advanced Usage

If you want to bind this component to a FormControl, display alpha codes, or listen to more events (e.g., input changes), take advantage of these additional inputs and outputs:

    <ng-country-select
      [lang]="'en'"
      [formControl]="countryControl"
      [searchAllLanguages]="true"
      [showCodes]="true"
      [debounceTime]="200"
      [appearance]="'outline'"
      [placeholder]="'Search country'"
      (countrySelected)="onCountrySelect($event)"
      (inputChanged)="trackSearchTerm($event)"
    ></ng-country-select>
Enter fullscreen mode Exit fullscreen mode

8.1. Key Inputs

  • defaultCountry: Preselect a country from the start.

  • formControl: Two-way binding with Angular Reactive Forms.

  • lang: Choose the language (en, de, fr, es, it).

  • searchAllLanguages: Toggle multi-lingual searching on/off.

  • appearance: 'fill' | 'outline' to control the Material appearance.

  • placeholder: Override the search box placeholder.

  • disabled: Disable the entire component if needed.

8.2. Important Outputs

  • countrySelected: Emits a Country object when a user picks a country.

  • inputChanged: Emits a string for every typed character, useful for analytics or debugging.

  • closed: Triggers when the autocomplete panel closes.

9. Putting It All Together

Below is a more comprehensive example to illustrate how you might tie this into a reactive form:

    import { Component, OnInit } from '@angular/core';
    import { FormControl } from '@angular/forms';
    import { Country } from '@wlucha/ng-country-select';

    @Component({
      selector: 'app-root',
      template: `
        <h2>Advanced Country Selection 🌍</h2>
        <form>
          <ng-country-select
            [lang]="'es'"
            [formControl]="countryControl"
            [showCodes]="true"
            [searchAllLanguages]="true"
            [appearance]="'outline'"
            [placeholder]="'Elige tu país...'"
            (countrySelected)="onCountrySelected($event)"
            (inputChanged)="onInputChanged($event)"
          ></ng-country-select>
        </form>
        <p>Selected Country: {{ selectedCountryName }}</p>
      `
    })
    export class AppComponent implements OnInit {

      countryControl = new FormControl();
      selectedCountryName: string = '';

      ngOnInit(): void {
        // Optional: set default value in reactive form
        // countryControl.setValue({ name: 'Germany', alpha2: 'DE', ... })
      }

      onCountrySelected(country: Country): void {
        this.selectedCountryName = country.name;
        console.log('User selected:', country);
      }

      onInputChanged(term: string): void {
        console.log('User is typing:', term);
      }
    }
Enter fullscreen mode Exit fullscreen mode

In this snippet, we:

  1. Instantiate a FormControl to track the country.

  2. Listen for countrySelected to update our component state.

  3. Capture real-time user input from inputChanged.

  4. Display the user’s selection in the template.

10. Where to Go from Here?

10.1. Explore More Features

Check out the GitHub repository for deeper documentation, advanced use cases, and upcoming features like an ng-add schematic, more languages, and possibly richer flag options. Feel free to submit issues or pull requests if you spot a bug or have an idea for a new feature.

10.2. Contribute & Support

If you find this library helpful, show some love:

  • Star the repo on GitHub ⭐

  • Report bugs or suggest features

  • Share with your colleagues or community

Every small contribution helps make open-source tools more robust. 😍

10.3. Integrate in Production

Once satisfied with your setup, you can integrate the country select component wherever you need. It’s perfect for user registration forms, shipping address inputs, or dynamic dashboards that might filter data by region. Pair it with a good backend that handles localized content, and you’ll be serving up an exceptional user experience worldwide. 🌎

11. Conclusion

Implementing a country autocomplete in Angular no longer needs to be a daunting task. By harnessing the power of Angular Material and a specialized library like @wlucha/ng-country-select, you can quickly spin up a multilingual, flag-emoji-enhanced, and highly performant country picker in just a few steps.

Key takeaways:

  • You can avoid the headache of managing huge country lists and localization quirks.

  • The library is flexible enough to handle different Angular versions, from 16 to 19.

  • Searching by partial name, code, or localized name is super smooth — thanks to built-in RxJS support.

Give it a try, customize it to your needs, and watch your users enjoy a swift, intuitive location selection experience! 🎉

Thanks for reading, and happy coding!

Check out more details and the full documentation on the project’s GitHub page: @wlucha/ng-country-select.

Top comments (0)