Top Related Projects
Angular powered Bootstrap
The Most Complete Angular UI Component Library
Material design for AngularJS
:boom: Customizable Angular UI Library based on Eva Design System :new_moon_with_face::sparkles:Dark Mode
📝 JSON powered / Dynamic forms for Angular
Quick Overview
ng-select is a lightweight and highly customizable Angular select component. It provides a powerful and flexible solution for creating dropdown menus, multi-select interfaces, and autocomplete functionality in Angular applications. The library is designed to be easy to use while offering advanced features for complex use cases.
Pros
- Extensive customization options for appearance and behavior
- Supports both single and multiple selection modes
- Integrates well with Angular forms and reactive programming
- Offers virtual scrolling for handling large datasets efficiently
Cons
- Learning curve for advanced customization and complex scenarios
- Some users report occasional performance issues with very large datasets
- Documentation could be more comprehensive for certain advanced features
- May require additional styling effort to match specific design requirements
Code Examples
- Basic usage with static data:
@Component({
selector: 'app-example',
template: `
<ng-select [items]="cities"
bindLabel="name"
bindValue="id"
[(ngModel)]="selectedCityId">
</ng-select>
`
})
export class ExampleComponent {
cities = [
{ id: 1, name: 'New York' },
{ id: 2, name: 'London' },
{ id: 3, name: 'Tokyo' }
];
selectedCityId: number;
}
- Multiple selection with custom template:
@Component({
selector: 'app-example',
template: `
<ng-select [items]="users"
bindLabel="name"
[multiple]="true"
[(ngModel)]="selectedUsers">
<ng-template ng-option-tmp let-item="item">
<img [src]="item.avatar" width="30" height="30">
{{item.name}}
</ng-template>
</ng-select>
`
})
export class ExampleComponent {
users = [
{ id: 1, name: 'John', avatar: 'path/to/avatar1.jpg' },
{ id: 2, name: 'Jane', avatar: 'path/to/avatar2.jpg' },
{ id: 3, name: 'Bob', avatar: 'path/to/avatar3.jpg' }
];
selectedUsers: any[];
}
- Asynchronous data loading:
@Component({
selector: 'app-example',
template: `
<ng-select [items]="people$ | async"
bindLabel="name"
[typeahead]="peopleInput$"
[(ngModel)]="selectedPerson">
</ng-select>
`
})
export class ExampleComponent {
peopleInput$ = new Subject<string>();
people$: Observable<any[]>;
constructor(private http: HttpClient) {
this.people$ = this.peopleInput$.pipe(
debounceTime(200),
distinctUntilChanged(),
switchMap(term => this.http.get<any[]>(`api/people?search=${term}`))
);
}
}
Getting Started
-
Install ng-select:
npm install @ng-select/ng-select
-
Import NgSelectModule in your app.module.ts:
import { NgSelectModule } from '@ng-select/ng-select'; @NgModule({ imports: [ // ... other imports NgSelectModule ] }) export class AppModule { }
-
Use ng-select in your component:
@Component({ selector: 'app-example', template: ` <ng-select [items]="items" [(ngModel)]="selectedItem"> </ng-select> ` }) export class ExampleComponent { items = ['Item 1', 'Item 2', 'Item 3']; selectedItem: string; }
Competitor Comparisons
Angular powered Bootstrap
Pros of ng-bootstrap
- Comprehensive set of Bootstrap components for Angular
- Actively maintained with regular updates
- Large community and extensive documentation
Cons of ng-bootstrap
- Larger bundle size due to full Bootstrap integration
- Steeper learning curve for developers new to Bootstrap
Code Comparison
ng-bootstrap:
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@NgModule({
imports: [NgbModule],
// ...
})
export class AppModule { }
ng-select:
import { NgSelectModule } from '@ng-select/ng-select';
@NgModule({
imports: [NgSelectModule],
// ...
})
export class AppModule { }
Key Differences
- ng-bootstrap provides a full suite of Bootstrap components, while ng-select focuses solely on select/dropdown functionality
- ng-select offers more customization options for select inputs
- ng-bootstrap requires Bootstrap CSS, whereas ng-select has its own styling
Use Cases
- Choose ng-bootstrap for projects requiring multiple Bootstrap components
- Opt for ng-select when advanced select functionality is the primary need
Community and Support
- Both projects have active communities on GitHub
- ng-bootstrap has more stars and contributors due to its broader scope
Performance Considerations
- ng-select may have better performance for select-specific use cases
- ng-bootstrap's larger bundle size might impact initial load times
The Most Complete Angular UI Component Library
Pros of PrimeNG
- Comprehensive UI component library with a wide range of components beyond just select
- Extensive theming and customization options
- Active development and regular updates
Cons of PrimeNG
- Larger bundle size due to the extensive component library
- Steeper learning curve for utilizing all features
- May require additional configuration for optimal performance
Code Comparison
ng-select:
<ng-select [items]="cities"
bindLabel="name"
bindValue="id"
[(ngModel)]="selectedCityId">
</ng-select>
PrimeNG:
<p-dropdown [options]="cities"
optionLabel="name"
optionValue="id"
[(ngModel)]="selectedCityId">
</p-dropdown>
Both libraries offer similar functionality for creating dropdown selects, with slight differences in attribute naming. PrimeNG uses p-dropdown
component, while ng-select uses ng-select
. The binding of options and values is achieved through similar attributes, making it relatively easy to switch between the two if needed.
PrimeNG provides a more extensive set of UI components, which can be beneficial for larger projects requiring diverse interface elements. However, this comes at the cost of a larger bundle size and potentially more complex setup. ng-select, being more focused on select functionality, offers a lighter-weight solution with a simpler learning curve, but may require additional libraries for other UI components.
Material design for AngularJS
Pros of Material
- Comprehensive UI component library with a wide range of components
- Follows Material Design guidelines for consistent and modern look
- Strong community support and regular updates from the Angular team
Cons of Material
- Larger bundle size due to the extensive component library
- Steeper learning curve for customization and theming
- May require additional setup for custom styling
Code Comparison
Material select component:
<mat-form-field>
<mat-label>Select an option</mat-label>
<mat-select [(ngModel)]="selectedOption">
<mat-option *ngFor="let option of options" [value]="option.value">
{{option.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
ng-select component:
<ng-select [items]="options"
bindLabel="viewValue"
bindValue="value"
[(ngModel)]="selectedOption">
</ng-select>
Summary
Material offers a comprehensive UI library with consistent design, while ng-select focuses specifically on select components. Material has a larger ecosystem but may be overkill for projects only needing select functionality. ng-select provides a more lightweight and flexible solution for select inputs, with easier customization options. The choice between the two depends on project requirements and the need for additional UI components beyond select inputs.
:boom: Customizable Angular UI Library based on Eva Design System :new_moon_with_face::sparkles:Dark Mode
Pros of Nebular
- Comprehensive UI kit with a wide range of components and themes
- Built-in authentication and security features
- Extensive documentation and active community support
Cons of Nebular
- Steeper learning curve due to its extensive feature set
- Potentially larger bundle size for smaller projects
- May require more configuration and setup compared to simpler libraries
Code Comparison
ng-select:
<ng-select [items]="cities"
bindLabel="name"
bindValue="id"
[(ngModel)]="selectedCityId">
</ng-select>
Nebular:
<nb-select [(selected)]="selectedCity">
<nb-option *ngFor="let city of cities" [value]="city">
{{ city.name }}
</nb-option>
</nb-select>
Summary
ng-select is a lightweight, focused library for creating customizable select dropdowns in Angular applications. It's easy to use and integrate, making it ideal for projects that primarily need robust select functionality.
Nebular, on the other hand, is a comprehensive UI kit offering a wide range of components and features beyond just select dropdowns. It provides a complete design system, including themes, layouts, and authentication modules. While more complex, Nebular is suitable for larger projects requiring a consistent and feature-rich UI framework.
Choose ng-select for simpler projects or when you need a powerful select component. Opt for Nebular when building larger applications that benefit from a complete UI ecosystem and don't mind the additional complexity.
📝 JSON powered / Dynamic forms for Angular
Pros of ngx-formly
- More comprehensive form-building solution, handling complex form structures
- Highly customizable with support for custom field types and templates
- Integrates well with various UI frameworks and form validation libraries
Cons of ngx-formly
- Steeper learning curve due to its extensive feature set
- May be overkill for simple form scenarios
- Requires more setup and configuration compared to ng-select
Code Comparison
ng-select:
<ng-select [items]="cities"
bindLabel="name"
bindValue="id"
[(ngModel)]="selectedCityId">
</ng-select>
ngx-formly:
<form [formGroup]="form">
<formly-form [form]="form" [fields]="fields" [model]="model">
</formly-form>
</form>
While ng-select focuses on providing a powerful select component, ngx-formly offers a more comprehensive solution for building entire forms dynamically. ng-select is easier to implement for simple select scenarios, while ngx-formly provides greater flexibility and control over complex form structures.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Angular ng-select - Lightweight all in one UI Select, Multiselect and Autocomplete
See Demo page.
Versions
Angular | ng-select |
---|---|
>=19.0.0 <20.0.0 | v14.x |
>=18.0.0 <19.0.0 | v13.x |
>=17.0.0 <18.0.0 | v12.x |
>=16.0.0 <17.0.0 | v11.x |
>=15.0.0 <16.0.0 | v10.x |
>=14.0.0 <15.0.0 | v9.x |
>=13.0.0 <14.0.0 | v8.x |
>=12.0.0 <13.0.0 | v7.x |
>=11.0.0 <12.0.0 | v6.x |
>=10.0.0 <11.0.0 | v5.x |
>=9.0.0 <10.0.0 | v4.x |
>=8.0.0 <9.0.0 | v3.x |
>=6.0.0 <8.0.0 | v2.x |
v5.x.x | v1.x |
Browser Support
ng-select
supports all browsers supported by Angular. For current list, see https://angular.io/guide/browser-support#browser-support. This includes the following specific versions:
Chrome 2 most recent versions
Firefox latest and extended support release (ESR)
Edge 2 most recent major versions
Safari 2 most recent major versions
iOS 2 most recent major versions
Android 2 most recent major versions
Table of contents
Features
- Custom binding to property or object
- Custom option, label, header and footer templates
- Virtual Scroll support with large data sets (>5000 items).
- Infinite scroll
- Keyboard navigation
- Multiselect
- Flexible autocomplete with client/server filtering
- Custom search
- Custom tags
- Append to
- Group items
- Output events
- Accessibility
- Good base functionality test coverage
- Themes
Warning
Library is under active development and may have API breaking changes for subsequent major versions after 1.0.0.
Getting started
Step 1: Install ng-select
:
NPM
npm install --save @ng-select/ng-select
YARN
yarn add @ng-select/ng-select
Step 2:
Standalone: Import NgSelectComponent and other necessary directives directly:
import { NgLabelTemplateDirective, NgOptionTemplateDirective, NgSelectComponent } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'example',
standalone: true,
template: './example.component.html',
styleUrl: './example.component.scss',
imports: [
NgLabelTemplateDirective,
NgOptionTemplateDirective,
NgSelectComponent,
],
})
export class ExampleComponent {}
NgModule: 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): Configuration
You 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';
}
Usage
Define 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">
@for (car of cars; track car.id) {
<ng-option [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
SystemJS
If 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',
}
API
Inputs
Input | Type | Default | Required | Description |
---|---|---|---|---|
[addTag] | boolean | ((term: string) => any | Promise<any>) | false | no | Allows to create custom options. |
addTagText | string | Add item | no | Set custom text when using tagging |
appearance | string | underline | no | Allows to select dropdown appearance. Set to outline to add border instead of underline (applies only to Material theme) |
appendTo | string | null | no | Append dropdown to body or any other element using css selector. For correct positioning body should have position:relative |
bufferAmount | number | 4 | no | Used in virtual scrolling, the bufferAmount property controls the number of items preloaded in the background to ensure smoother and more seamless scrolling. |
bindValue | string | - | no | Object property to use for selected model. By default binds to whole object. |
bindLabel | string | label | no | Object property to use for label. Default label |
[closeOnSelect] | boolean | true | no | Whether to close the menu when a value is selected |
clearAllText | string | Clear all | no | Set custom text for clear all icon title |
[clearable] | boolean | true | no | Allow to clear selected value. Default true |
[clearOnBackspace] | boolean | true | no | Clear selected values one by one when clicking backspace. Default true |
[compareWith] | (a: any, b: any) => boolean | (a, b) => a === b | no | 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 | auto | no | Set the dropdown position on open |
[fixedPlaceholder] | boolean | false | no | Set placeholder visible even when an item is selected |
[groupBy] | string | Function | null | no | Allow to group items by key or function expression |
[groupValue] | (groupKey: string, children: any[]) => Object | - | no | Function expression to provide group value |
[selectableGroup] | boolean | false | no | Allow to select group when groupBy is used |
[selectableGroupAsModel] | boolean | true | no | Indicates whether to select all children or group itself |
[items] | Array<any> | [] | yes | Items array |
[loading] | boolean | - | no | You can set the loading state from the outside (e.g. async items loading) |
loadingText | string | Loading... | no | Set custom text when for loading items |
labelForId | string | - | no | Id to associate control with label. |
[markFirst] | boolean | true | no | Marks first item as focused when opening/filtering. |
[isOpen] | boolean | - | no | Allows manual control of dropdown opening and closing. true - won't close. false - won't open. |
maxSelectedItems | number | none | no | When multiple = true, allows to set a limit number of selection. |
[hideSelected] | boolean | false | no | Allows to hide selected items. |
[multiple] | boolean | false | no | Allows to select multiple items. |
notFoundText | string | No items found | no | Set custom text when filter returns empty result |
placeholder | string | - | no | Placeholder text. |
[searchable] | boolean | true | no | Allow to search for value. Default true |
[readonly] | boolean | false | no | Set ng-select as readonly. Mostly used with reactive forms. |
[searchFn] | (term: string, item: any) => boolean | null | no | Allow to filter by custom search function |
[searchWhileComposing] | boolean | true | no | Whether items should be filtered while composition started |
[trackByFn] | (item: any) => any | null | no | Provide custom trackBy function |
[clearSearchOnAdd] | boolean | true | no | Clears search input when item is selected. Default true . Default false when closeOnSelect is false |
[deselectOnClick] | boolean | false | no | Deselects a selected item when it is clicked in the dropdown. Default false . Default true when multiple is true |
[editableSearchTerm] | boolean | false | no | Allow to edit search query if option selected. Default false . Works only if multiple is false . |
[selectOnTab] | boolean | false | no | Select marked dropdown item using tab. Default false |
[openOnEnter] | boolean | true | no | Open dropdown using enter. Default true |
[typeahead] | Subject | - | no | Custom autocomplete or advanced filter. |
[minTermLength] | number | 0 | no | Minimum term length to start a search. Should be used with typeahead |
typeToSearchText | string | Type to search | no | Set custom text when using Typeahead |
[virtualScroll] | boolean | false | no | Enable virtual scroll for better performance when rendering a lot of data |
[inputAttrs] | { [key: string]: string } | - | no | Pass custom attributes to underlying input element |
[tabIndex] | number | - | no | Set tabindex on ng-select |
[preventToggleOnRightClick] | boolean | false | no | Prevent opening of ng-select on right mouse click |
[keyDownFn] | ($event: KeyboardEvent) => bool | true | no | Provide custom keyDown function. Executed before default handler. Return false to suppress execution of default key down handlers |
Outputs
Output | Description |
---|---|
(add) | Fired when item is added while [multiple]="true" . Outputs added item |
(blur) | Fired on select blur |
(change) | Fired on model change. Outputs whole model |
(close) | Fired on select dropdown close |
(clear) | Fired on clear icon click |
(focus) | Fired on select focus |
(search) | Fired while typing search term. Outputs search term with filtered items |
(open) | Fired on select dropdown open |
(remove) | Fired when item is removed while [multiple]="true" |
(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. |
Methods
Name | Description |
---|---|
open | Opens the select dropdown panel |
close | Closes the select dropdown panel |
focus | Focuses the select element |
blur | Blurs the select element |
Other
Name | Type | Description |
---|---|---|
[ngOptionHighlight] | directive | Highlights search term in option. Accepts search term. Should be used on option element. README |
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. |
Custom selection logic
Ng-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 Detection
Ng-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 styles
If 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 state
By 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;
}
Contributing
Contributions 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.
Development
Perform the clone-to-launch steps with these terminal commands.
Run demo page in watch mode
git clone https://github.com/ng-select/ng-select
cd ng-select
yarn
yarn run start
Testing
yarn run test
or
yarn run test:watch
Release
To release to npm just run ./release.sh
, of course if you have permissions ;)
Inspiration
This component is inspired by React select and Virtual scroll. Check theirs amazing work and components :)
Top Related Projects
Angular powered Bootstrap
The Most Complete Angular UI Component Library
Material design for AngularJS
:boom: Customizable Angular UI Library based on Eva Design System :new_moon_with_face::sparkles:Dark Mode
📝 JSON powered / Dynamic forms for Angular
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot