Angular ng-select - Lightweight all in one UI Select, Multiselect and Autocomplete
See Demo page.
Angular ng-select Versions
Warning
Library is under active development and may have API breaking changes for subsequent major versions after 1.0.0.
Getting started
ng-select
:
Step 1: Install
npm install --save @ng-select/ng-select
yarn add @ng-select/ng-select
Step 2: Import the NgSelectModule and angular FormsModule module:
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [NgSelectModule, FormsModule],
bootstrap: [AppComponent]
export class AppModule {}
Step 3: Include a theme:
To allow customization and theming,
ng-select
bundle includes only generic styles that are necessary for correct layout and positioning. To get full look of the control, include one of the themes in your application. If you're using the Angular CLI, you can add this to your
styles.scss
or include it in
.angular-cli.json
(Angular v5 and below) or
angular.json
(Angular v6 onwards).
@import "~@ng-select/ng-select/themes/default.theme.css";
// ... or
@import "~@ng-select/ng-select/themes/material.theme.css";
Step 4 (Optional): ConfigurationYou can also set global configuration and localization messages by injecting NgSelectConfig service,
typically in your root component, and customize the values of its properties in order to provide default values.
constructor(private config: NgSelectConfig) {
this.config.notFoundText = 'Custom not found';
this.config.appendTo = 'body';
// set the bindValue to global config when you use the same
// bindValue in most of the place.
// You can also override bindValue for the specified template
// by defining `bindValue` as property
// Eg : <ng-select bindValue="some-new-value"></ng-select>
this.config.bindValue = 'value';
UsageDefine options in your consuming component:
@Component({...})
export class ExampleComponent {
selectedCar: number;
cars = [
{ id: 1, name: 'Volvo' },
{ id: 2, name: 'Saab' },
{ id: 3, name: 'Opel' },
{ id: 4, name: 'Audi' },
In template use ng-select
component with your options
<!--Using ng-option and for loop-->
<ng-select [(ngModel)]="selectedCar">
<ng-option *ngFor="let car of cars" [value]="car.id">{{car.name}}</ng-option>
</ng-select>
<!--Using items input-->
<ng-select [items]="cars"
bindLabel="name"
bindValue="id"
[(ngModel)]="selectedCar">
</ng-select>
For more detailed examples see Demo page
SystemJSIf you are using SystemJS, you should also adjust your configuration to point to the UMD bundle.
In your systemjs config file, map
needs to tell the System loader where to look for ng-select
:
map: {
'@ng-select/ng-select': 'node_modules/@ng-select/ng-select/bundles/ng-select.umd.js',
Input
Default
Required
Description
Inputsunderline
Allows to select dropdown appearance. Set to outline
to add border instead of underline (applies only to Material theme)
appendTo
string
Append dropdown to body or any other element using css selector. For correct positioning body
should have position:relative
bindValue
string
Object property to use for selected model. By default binds to whole object.
bindLabel
string
label
Object property to use for label. Default label
[closeOnSelect]
boolean
Whether to close the menu when a value is selected
clearAllText
string
Clear all
Set custom text for clear all icon title
[clearable]
boolean
Allow to clear selected value. Default true
[clearOnBackspace]
boolean
Clear selected values one by one when clicking backspace. Default true
[compareWith]
(a: any, b: any) => boolean
(a, b) => a === b
A function to compare the option values with the selected values. The first argument is a value from an option. The second is a value from the selection(model). A boolean should be returned.
dropdownPosition
bottom
| top
| auto
Set the dropdown position on open
[groupBy]
string
| Function
Allow to group items by key or function expression
[groupValue]
(groupKey: string, children: any[]) => Object
Function expression to provide group value
[selectableGroup]
boolean
false
Allow to select group when groupBy is used
[selectableGroupAsModel]
boolean
Indicates whether to select all children or group itself
[items]
Array<any>
Items array
[loading]
boolean
You can set the loading state from the outside (e.g. async items loading)
loadingText
string
Loading...
Set custom text when for loading items
labelForId
string
Id to associate control with label.
[markFirst]
boolean
Marks first item as focused when opening/filtering.
[isOpen]
boolean
Allows manual control of dropdown opening and closing. True
- won't close. False
- won't open.
maxSelectedItems
number
When multiple = true, allows to set a limit number of selection.
[hideSelected]
boolean
false
Allows to hide selected items.
[multiple]
boolean
false
Allows to select multiple items.
notFoundText
string
No items found
Set custom text when filter returns empty result
placeholder
string
Placeholder text.
[searchable]
boolean
Allow to search for value. Default true
[readonly]
boolean
false
Set ng-select as readonly. Mostly used with reactive forms.
[searchFn]
(term: string, item: any) => boolean
Allow to filter by custom search function
[searchWhileComposing]
boolean
Whether items should be filtered while composition started
[trackByFn]
(item: any) => any
Provide custom trackBy function
[clearSearchOnAdd]
boolean
Clears search input when item is selected. Default true
. Default false
when closeOnSelect is false
[deselectOnClick]
boolean
false
Deselects a selected item when it is clicked in the dropdown. Default false
. Default true
when multiple is true
[editableSearchTerm]
boolean
false
Allow to edit search query if option selected. Default false
. Works only if multiple is false
.
[selectOnTab]
boolean
false
Select marked dropdown item using tab. Default false
[openOnEnter]
boolean
Open dropdown using enter. Default true
[typeahead]
Subject
Custom autocomplete or advanced filter.
[minTermLength]
number
Minimum term length to start a search. Should be used with typeahead
typeToSearchText
string
Type to search
Set custom text when using Typeahead
[virtualScroll]
boolean
false
Enable virtual scroll for better performance when rendering a lot of data
[inputAttrs]
{ [key: string]: string }
Pass custom attributes to underlying input
element
[tabIndex]
number
Set tabindex on ng-select
[keyDownFn]
($event: KeyboardEvent) => bool
Provide custom keyDown function. Executed before default handler. Return false to suppress execution of default key down handlers
Output
Description
(scroll)
Fired when scrolled. Provides the start and end index of the currently available items. Can be used for loading more items in chunks before the user has scrolled all the way to the bottom of the list.
(scrollToEnd)
Fired when scrolled to the end of items. Can be used for loading more items in chunks.
Outputs
Description
NgSelectConfig
configuration
Configuration provider for the NgSelect component. You can inject this service and provide application wide configuration.
SELECTION_MODEL_FACTORY
service
DI token for SelectionModel implementation. You can provide custom implementation changing selection behaviour.
Methods
Custom selection logicNg-select allows to provide custom selection implementation using SELECTION_MODEL_FACTORY
. To override default logic provide your factory method in your angular module.
// app.module.ts
providers: [
{ provide: SELECTION_MODEL_FACTORY, useValue: <SelectionModelFactory>CustomSelectionFactory }
// selection-model.ts
export function CustomSelectionFactory() {
return new CustomSelectionModel();
export class CustomSelectionModel implements SelectionModel {
Change DetectionNg-select component implements OnPush
change detection which means the dirty checking checks for immutable
data types. That means if you do object mutations like:
this.items.push({id: 1, name: 'New item'})
Component will not detect a change. Instead you need to do:
this.items = [...this.items, {id: 1, name: 'New item'}];
This will cause the component to detect the change and update. Some might have concerns that
this is a pricey operation, however, it is much more performant than running ngDoCheck
and
constantly diffing the array.
Custom stylesIf you are not happy with default styles you can easily override them with increased selector specificity or creating your own theme. This applies if you are using no ViewEncapsulation
or adding styles to global stylesheet. E.g.
<ng-select class="custom"></ng-select>
.ng-select.custom {
border:0px;
min-height: 0px;
border-radius: 0;
.ng-select.custom .ng-select-container {
min-height: 0px;
border-radius: 0;
If you are using ViewEncapsulation
, you could use special ::ng-deep
selector which will prevent scoping for nested selectors altough this is more of a workaround and we recommend using solution described above.
.ng-select.custom ::ng-deep .ng-select-container {
min-height: 0px;
border-radius: 0;
WARNING: Keep in mind that ng-deep is deprecated and there is no alternative to it yet. See Here.
Validation stateBy default when you use reactive forms validators or template driven forms validators css class ng-invalid
will be applied on ng-select. You can show errors state by adding custom css style
ng-select.ng-invalid.ng-touched .ng-select-container {
border-color: #dc3545;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px #fde6e8;
ContributingContributions are welcome. You can start by looking at issues with label Help wanted or creating new Issue with proposal or bug report.
Note that we are using https://conventionalcommits.org/ commits format.
DevelopmentPerform the clone-to-launch steps with these terminal commands.
Run demo page in watch modegit clone https://github.com/ng-select/ng-select
cd ng-select
yarn run start
Testingyarn run test
yarn run test:watch
ReleaseTo release to npm just run ./release.sh
, of course if you have permissions ;)
Inspiration