DEV Community

Cover image for How to fetch data from the backend for PrimeNg drop down
Alphaexcel
Alphaexcel

Posted on • Edited on

How to fetch data from the backend for PrimeNg drop down

When using components in PrimeNG, depending on the framework of your choice—which may be Angular, React, or another framework—you'll often need to fetch data from a backend and display it to users.

Today, we'll be discussing how to use the PrimeNG Dropdown component to display data fetched from a backend service.

Getting Started

The first thing you need to do is visit the PrimeNG documentation:

This link takes you directly to the Dropdown component documentation.

Next, install PrimeNG and PrimeIcons using the following commands:

npm install primeng --save
npm install primeicons --save
Enter fullscreen mode Exit fullscreen mode

Once they have been installed successfully, you'll be able to import PrimeNG modules into your application.

For example:

import { AccordionModule } from 'primeng/accordion';
import { MenuItem } from 'primeng/api';
Enter fullscreen mode Exit fullscreen mode

To use the Dropdown component specifically, import:

import { DropdownModule } from 'primeng/dropdown';

Then add it to your module imports.

A Quick Note on PrimeNG Modules

If you have worked with UI libraries such as Angular Material, PrimeNG, or similar component libraries, you may have noticed that each component requires its corresponding module to be imported.

This approach helps improve application performance by ensuring that only the components you need are included in the final build.

A good practice is to create a shared module where you import and export all the PrimeNG modules you frequently use. This makes your project easier to maintain and reduces repetitive imports across your application.


Fetching Data from the Backend

The first step is to create an empty array that will hold the data returned from your backend.

Next, subscribe to a service that contains the function responsible for fetching the data.

A typical example looks like this:

this.cityService.getCities().subscribe(data => {
  this.cities = data;
});
Enter fullscreen mode Exit fullscreen mode

Once the data has been assigned to the array, you can bind it to your PrimeNG Dropdown.


Creating the Dropdown

The PrimeNG Dropdown component looks like this:

<p-dropdown
    [options]="cities"
    [(ngModel)]="selectedCity"
    optionLabel="name">
</p-dropdown>
Enter fullscreen mode Exit fullscreen mode

Let's look at what each property does:

Property| Description
"options"| Contains the array of data displayed in the dropdown
"ngModel"| Stores the selected value
"optionLabel"| Determines which property is displayed to the user

In this example, "cities" represents the array containing the data returned from the backend.

To better understand how it works, let's use some mock data.


Understanding the Data Structure

The following example comes directly from the PrimeNG documentation:

interface City {
    name: string;
    code: string;
}

export class DropdownDemo {

    cities: City[];

    selectedCity: City;

    constructor() {
        this.cities = [
            { name: 'New York', code: 'NY' },
            { name: 'Rome', code: 'RM' },
            { name: 'London', code: 'LDN' },
            { name: 'Istanbul', code: 'IST' },
            { name: 'Paris', code: 'PRS' }
        ];
    }

}

Here, "cities" is an array of objects.
Enter fullscreen mode Exit fullscreen mode

Each object contains two properties:

- "name"
- "code"
Enter fullscreen mode Exit fullscreen mode

The Dropdown component uses the "optionLabel" property to determine which of these values should be displayed.


Understanding optionLabel

Suppose we have the following Dropdown:

<p-dropdown
    [options]="cities"
    [(ngModel)]="selectedCity"
    optionLabel="name">
</p-dropdown>
Enter fullscreen mode Exit fullscreen mode

Since "optionLabel" is set to "name", the dropdown will display:

New York
Rome
London
Istanbul
Paris
Enter fullscreen mode Exit fullscreen mode

However, if we change the component to:

<p-dropdown
    [options]="cities"
    [(ngModel)]="selectedCity"
    optionLabel="code">
</p-dropdown>
Enter fullscreen mode Exit fullscreen mode

The dropdown will instead display:

NY
RM
LDN
IST
PRS
Enter fullscreen mode Exit fullscreen mode

PrimeNG simply displays whichever property you specify in the "optionLabel".


Common Mistakes

  1. Using the Wrong Property Name

Suppose your API returns:

[
{
"cityName": "Lagos"
}
]
`plaintext
This will not work:


optionLabel="name"
plaintext

Because the property is called "cityName", not "name".

Instead, use:


optionLabel="cityName"
plaintext

  1. Forgetting to Subscribe

This won't work:

this.cities = this.cityService.getCities();
typescript
You must subscribe to the Observable:

this.cityService.getCities().subscribe(data => {
this.cities = data;
});
typescript

  1. Forgetting FormsModule

If you're using "ngModel", make sure you've imported:
`
import { FormsModule } from '@angular/forms';

`

Conclusion

Working with a PrimeNG Dropdown becomes much easier once you understand three key concepts:

  • "options" supplies the data.
  • "optionLabel" determines what users see.
  • "ngModel" stores the selected value.

Whether your data comes from a hardcoded array, a REST API, Firebase, or another backend service, the process remains exactly the same once the data is assigned to the array referenced by "options".

What was the first PrimeNG component that gave you trouble when you started using the library?

Let me know in the comments.

Happy coding!

Top comments (0)