Saturday, August 4, 2018

Primeng Dropdown - Basic Examples with tutorials

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. The element can be plain strings, JSON array or Objects.Primeng has set of rich UI Elements for  Agular Framework on typescript from Primefaces team. already documented different post about primeng framework

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
This tutorial will work with different angular versions2/4/5/6 on typescript language. 5 and 6 is recommended versions as these are latest supported versions.

Angular/typescript dropdown basic example

The first step is to make sure install and integrate with Angular cli as per previous posts and like given above. Once done. Now you are able to access primeng modules. Primeng provides each component in the form of modules, a Dropdown module is DropdownModule For Dropdown to use in the angular application, First you need to import and declare DropdownModule which you need to declare in your module as below app.module.ts, Import and declare
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 { }
App.component.ts This is typescript coded file component with employes object declared and initialized with JSON object. By default, primeng dropdown accepts JSON object with a key of label and value of value. if you want a custom object, we will see next example
import { Component, OnInit } from '@angular/core';
import {SelectItem} from 'primeng/api';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  employes: SelectItem[];
  selectedEmploye: any;

  constructor(){
    this.employes = [
      {label:'Select Employee', value:null},
      {label:'Franc', value:1},
      {label:'Kiran', value:2},
      {label:'John', value:3},
    ];
  }
ngOnInit(){
}
}
app.component.html dropdown options holds array list in the form json object. ngModel is specified to have two way binding between your component and Html element
<div style="text-align: center;">
<h1>
      Primeng Angular 6 Dropdown Demo
   </h1>
</div>
<h3 class="basic">
Basci Dropdown</h3>
<p-dropdown employes="" ngmodel="" options="" selectedemploye=""></p-dropdown>
Selected Employee: {{selectedEmploye }}
And the output of the above code is
Angular 6 primeng Dropdown example

OptionLabel example 

if options list is of custom objects, we need to provide optionLabel property as the name of the option
<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>
app.component.ts
  countries:Country[];
  selectedCountry: Country;
    this.countries = [
      {name: 'India', code: 'IND'},
      {name: 'United States of America', code: 'USA'},
      {name: 'United Kingdom', code: 'UK'},
    ];

Modal Driven Form Example

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.

Dropdown style and Icon Change

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]

Related article


EmoticonEmoticon