Display Items in DropDown Angular
Select Option Vs Ng-select for displaying drop down items
Introduction
In this blog, we are going to display multiple items in a drop down using two methods:
Ng-select :
- Installing ng-select
i.using npm
npm install --save @ng-select/ng-select
ii.using yarn
yarn add @ng-select/ng-select
To confirm if ng-select is installed,check you package.json file dependencies section for:
"@ng-select/ng-select": "^8.1.1",
N.B version may vary depending on when you will install
2. Import the NgSelectModule into your app.module.ts or yourcustomemodule.module.ts
N.B you can also import FormsModule, ReactiveFormsModule for the form field.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';@NgModule({declarations: [AppComponent],imports: [BrowserModule,AppRoutingModule,NgSelectModule,FormsModule,ReactiveFormsModule,],providers: [],bootstrap: [AppComponent]
})
export class AppModule { }
3. Include theme in your angular.json or style.css
@import "~@ng-select/ng-select/themes/default.theme.css";
// ... or
@import "~@ng-select/ng-select/themes/material.theme.css";
3. Create a select form field using ng-select. You can remove the style (style=”margin-top: 20em;”) when working on a real form. Do this in your app.component.html or yourcustom.component.html.
<div class="container center" style="margin-top: 20em;">
<form>
<div class="col-md-6 form-group mb-3">
<ng-select class="custom" [items]="fruits" bindLabel="name" bindValue="id" placeholder="Select Fruit:"></ng-select>
</div>
</form>
</div>
N.B bindLabel is the key of name to be displayed
e.g
{id:1,name:"Mangoes"},
{id:1,description:"Mangoes"},
4. Create an array of fruits to display in the drop down in your app.component.ts or yourcustom.component.ts
import { Component, OnInit } from '@angular/core';@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})export class AppComponent {fruits=[
{id:1,name:"Mangoes"},
{id:2, name:"Oranges"},
{id:3, name:"WaterMelons"}
]
}
5.Run your application
ng serve
click on the drop down
Select an Item from drop down
Select Option
This does not require installation of packages. You manually loop through an array of items using *ngFor
click on dropdown
Code
<div class="container center" style="margin-top: 20em;">
<form>
<div class="form-group col-sm-6">
<select id="fruit" class="custom-select form-control" placeholder="Select Fruit:">
<option value='' disabled selected>Select Fruit Type*</option>
<option *ngFor="let fruit of fruits" [value]="fruit?.id">
{{fruit?.name | titlecase}}
</option>
</select>
</div>
</form>
</div>