Primeng Dropdown Component | Angular Dropdown list Example


In this tutorial, We are going to learn the basics of Primeng Dropdown with examples. The dropdown is a UI element that displays a list of elements, which allows the user to select one element from the list of elements. The element can be plain strings, JSON array or javascript Objects. Primeng has set of rich UI Elements for  Agular Framework on typescript from Primefaces team.

You can check my previous posts on primeng framework.

primeng Angular dropdown features

The following are a list of Inbuilt features supported

  • Customize the way look and feel styles
  • Custom Content and label using ngTemplate
  • Remote Binding with REST API
  • Filtering
  • Grouping

With abovel all features already supported, developer job is easy to focus on business functionality. In addition, you will get fully tested component.

This tutorial will work with different angular versions /4/5/6/7/8/9 on typescript language. 8 and 9 versions are recommended versions as these are latest supported versions.

Integration primeng dropdown into existing angular application

This tutorials covers the Integration of primeng dropdown into existing angular applicaiton, if you want to start the application from scratch, you check my previous Angular Application from scratch using primeng framework post.

First install the primeng depedencies primeng and primeiconsusing npm command

npm install primeng --save
npm install primeicons --save
npm install @angular/cdk --save

Above code installs the dependencies and make an entrie in package.JSON,

primeng modules provides various components in the form modules, For example, DropdownModule is a angular module which provides dropdown or select box component.

primeicons npm' module provides icons provided by primefaces team. Please check this add icons to primeng’ post to add icons support to your module. This is important step and if not configured correctly, icons not visible. `@angular/cdk’ - This npm module is required if scrolling support needs in dropdown.

Configure css styles in styles.css

@import "~primeicons/primeicons.css";
@import "~primeng/resources/themes/nova-dark/theme.css";
@import "~primeng/resources/primeng.min.css";

with the above steps, primeng npm modules are installed successfully in your application.

Primeng provides each component in the form of angular modules. Therfore, import ‘DropdownModule’ into your application as below

Configured DropdownModule in import section of your app.module.ts. After that, all primeng dropdown components/directives can be used in your applicaiton.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {DropdownModule} from 'primeng/dropdown'; // include this for dropdown support
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    DropdownModule // dropdown support
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas:[CUSTOM_ELEMENTS_SCHEMA]

})
export class AppModule { }

This is one time process per your applicaiton.

Now, you are ready to go creating first dropdown example.

First, Create a Simple angular basic-dropdown.component using ng g c nameofcomponent command

This creates following files in the existing application

  • basic-dropdown.component.html
  • basic-dropdown.component.ts files
  • basic-dropdown.component.css

basic-dropdown.component.ts file

This is typescript component file component which processing logic for display the UI element

First, created List of Employee objects of type Array SelectedItem Primeng dropdown supports SelectedItem or Custom array of objects. By default, It supports SelectedItem Each SelectedItem accepts key of label and value of value only. We will cover in next example if object is of custom type other than name and value.

In Constructor, employes object is populated and initialized with fixed values. selectedEmploye is an object to hold selected dropdown value, which is two way binding reference variable.

import { Component, OnInit } from "@angular/core";
import { SelectItem } from "primeng";

@Component({
  selector: "app-basic-dropdown",
  templateUrl: "./basic-dropdown.component.html",
  styleUrls: ["./basic-dropdown.component.css"]
})
export class BasicDropdownComponent implements OnInit {
  employes: SelectItem[];
  selectedEmploye: SelectItem;

  constructor() {
    this.employes = [
      { label: "Select Employee", value: null },
      { label: "Franc", value: 1 },
      { label: "Kiran", value: 2 },
      { label: "John", value: 3 }
    ];
  }

  ngOnInit() {}
}

basic-dropdown.component.html file

This is html template component file, which displays actual component on browser. In this file,p-dropdown component is used in this html file, It has an option attribute

Option attribute accepts array of items, Here SelectItem object is used, SelectItem object contains label and value selected item from dropdown is populated using selectedEmployee Object of SelectedItem.

selectedEmploye is mapped to component using ngModel with two way binding which assigns data between component and Html element.

<p>Simple Dropdown Example</p>

<p-dropdown [options]="employes"   [(ngModel)]="selectedEmploye"></p-dropdown>

<br>
<p>selected Employe: {{selectedEmploye? selectedEmploye.name:'none' }}</p>

And the output of the above code is

Angular 6 primeng Dropdown example

OptionLabel example 

In the Above example, Covered default format of label and value of an object.

In real time applications, The data mapped to dropdown is in different format. Suppose, we have a collection of countries with each country contains name and code properties. `OptionLabel’ attribute is used to map the custom label with data of an object.

Here is an Dropdown OptionLabel usage example

<p-dropdown [options]="countries" [(ngModel)]="selectedCountry" placeholder="Select a Country" optionLabel="name" [showClear]="true"></p-dropdown>
<p>Selected Country: {{selectedCountry? selectedCountry.name:'none' }}</p>
</div>

In the typescript component code

  countries:Country[];
  selectedCountry: Country;
    this.countries = [
      {name: 'India', code: 'IND'},
      {name: 'United States of America', code: 'USA'},
      {name: 'United Kingdom', code: 'UK'},
    ];

Model-driven form is one of the form handlings in any angular version. You need to import module - FormsModule, ReactiveFormsModule from ‘@angular/forms’ in your app module; formControlName element has the name of the form element Dropdown code can be changed to like as follows in HTML

<p-dropdown employes="" formcontrolname="selectedEmploye" options=""></p-dropdown>

ng-template custom label and content 

You can also use ng-template to customize the default behavior. The default behavior is showing the label on the drop-down. There are three templates - selectedItem template - Displayed Label can be customized to display icons, styles item template - customize the content in UI group template - customize the default behavior of the options group.

There are other features filter - filter by display name, Group - Group the elements under category in the display.

we can also customize/override  the default styles and icons, There is a predefined style to change it.ui-dropdown-trigger suppose to change the background color to green


body .ui-dropdown .ui-dropdown-trigger {
    background-color: green;
}

to change the icon, you have to use dropdownIcon attribute typescript component, declare like as below


export class AppComponent {
customIcon="fa fa-search";
}

using dropdownIcon attribute in HTML like below

<p-dropdown[dropdownIcon]="customIcon" placeholder=" Filter by name"></p-dropdown>

Important Events and properties

appendTo - Dropdown attached to the element. here elements are a body or any element. With this, we can avoid scrolling

  • onClick - Event callback is called when the component is clicked
  • onChange -  This will be called when the dropdown value changed
  • onFocus -  called when dropdown got focus
  • onBlur - called when dropdown changed focus to other elements in a page from this.

Fix for CUSTOM_ELEMENTS_SCHEMA Angular Error 

 The below error we used to get during configuring dropdown in application


Uncaught Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'p-dropdown'.
1. If 'p-dropdown' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'p-dropdown' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
</div>
<h3 class="first">Basci Dropdown</h3>
<p-dropdown [options]="employes" [ERROR ->][(ngModel)]="selectedEmploye" name="selectedEmploye" placeholder="Select a Employe" optionLabel="name"): ng:///AppModule/AppComponent.html@6:33
    at syntaxError (compiler.js:1016)
    at TemplateParser.push../node_modules/@angular/compiler/fesm5/compiler.js.TemplateParser.parse (compiler.js:14813)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate (compiler.js:23992)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate (compiler.js:23979)
    at compiler.js:23922
    at Set.forEach (<anonymous>)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents (compiler.js:23922)
    at compiler.js:23832
    at Object.then (compiler.js:1007)
    at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndComponents (compiler.js:23831)


Fixing this exception The reason p-dropdown is HTML tag using angular component which is custom HTML tag, not html5 inbuilt tag and we are using in our component. if the name of the component contains dash(-), then we need to do follow things You can add CUSTOM_ELEMENTS_SCHEMA as Schemas decorator to either in component or module. I am going to add it app.module.ts file which applies to all components in that module.


import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

  bootstrap: [AppComponent],
  schemas:
        [CUSTOM_ELEMENTS_SCHEMA]

primeng icons are not working or showing

Similar Posts