UNPKG

16.9 kBMarkdownView Raw
1 [![npm version](https://badge.fury.io/js/%40ng-select%2Fng-select.svg)](https://badge.fury.io/js/%40ng-select%2Fng-select)
2[![Coverage Status][coveralls-image]][coveralls-url]
3[![gzip bundle size](http://img.badgesize.io/https://unpkg.com/@ng-select/ng-select@latest/bundles/ng-select-ng-select.umd.min.js?compression=gzip&style=flat-square)][ng-select-url]
4[![ng-select channel on discord](https://img.shields.io/discord/873021904708059177.svg?style=flat-square)](https://discord.gg/ETyJTvKK)
5
6[coveralls-image]: https://coveralls.io/repos/github/ng-select/ng-select/badge.svg?branch=master
7[coveralls-url]: https://coveralls.io/github/ng-select/ng-select?branch=master
8[ng-select-url]: https://unpkg.com/@ng-select/ng-select@latest
9
10# Angular ng-select - Lightweight all in one UI Select, Multiselect and Autocomplete
11See [Demo](https://ng-select.github.io/ng-select) page.
12
13---
14
15## Versions
16
17| Angular | ng-select |
18|------------------|:---------:|
19| >=18.0.0 <19.0.0 | v13.x |
20| >=17.0.0 <18.0.0 | v12.x |
21| >=16.0.0 <17.0.0 | v11.x |
22| >=15.0.0 <16.0.0 | v10.x |
23| >=14.0.0 <15.0.0 | v9.x |
24| >=13.0.0 <14.0.0 | v8.x |
25| >=12.0.0 <13.0.0 | v7.x |
26| >=11.0.0 <12.0.0 | v6.x |
27| >=10.0.0 <11.0.0 | v5.x |
28| >=9.0.0 <10.0.0 | v4.x |
29| >=8.0.0 <9.0.0 | v3.x |
30| >=6.0.0 <8.0.0 | v2.x |
31| v5.x.x | v1.x |
32
33---
34## Browser Support
35`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:
36```angular2html
37Chrome 2 most recent versions
38Firefox latest and extended support release (ESR)
39Edge 2 most recent major versions
40Safari 2 most recent major versions
41iOS 2 most recent major versions
42Android 2 most recent major versions
43```
44Table of contents
45=================
46
47 * [Features](#features)
48 * [Getting started](#getting-started)
49 * [API](#api)
50 * [Change detection](#change-detection)
51 * [Custom styles](#custom-styles)
52 * [Validation state](#validation-state)
53 * [Contributing](#contributing)
54 * [Development](#development)
55 * [Inspiration](#inspiration)
56
57## Features
58- [x] Custom binding to property or object
59- [x] Custom option, label, header and footer templates
60- [x] Virtual Scroll support with large data sets (>5000 items).
61- [x] Infinite scroll
62- [x] Keyboard navigation
63- [x] Multiselect
64- [x] Flexible autocomplete with client/server filtering
65- [x] Custom search
66- [x] Custom tags
67- [x] Append to
68- [x] Group items
69- [x] Output events
70- [x] Accessibility
71- [x] Good base functionality test coverage
72- [x] Themes
73
74## Warning
75Library is under active development and may have API breaking changes for subsequent major versions after 1.0.0.
76
77## Getting started
78### Step 1: Install `ng-select`:
79
80#### NPM
81```shell
82npm install --save @ng-select/ng-select
83```
84#### YARN
85```shell
86yarn add @ng-select/ng-select
87```
88### Step 2:
89
90#### Standalone: Import NgSelectComponent and other necessary directives directly:
91```typescript
92import { NgLabelTemplateDirective, NgOptionTemplateDirective, NgSelectComponent } from '@ng-select/ng-select';
93import { FormsModule } from '@angular/forms';
94
95@Component({
96 selector: 'example',
97 standalone: true,
98 template: './example.component.html',
99 styleUrl: './example.component.scss',
100 imports: [
101 NgLabelTemplateDirective,
102 NgOptionTemplateDirective,
103 NgSelectComponent,
104 ],
105})
106export class ExampleComponent {}
107```
108
109#### NgModule: Import the NgSelectModule and angular FormsModule module:
110```typescript
111import { NgSelectModule } from '@ng-select/ng-select';
112import { FormsModule } from '@angular/forms';
113
114@NgModule({
115 declarations: [AppComponent],
116 imports: [NgSelectModule, FormsModule],
117 bootstrap: [AppComponent]
118})
119export class AppModule {}
120```
121
122### Step 3: Include a theme:
123To 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).
124
125```scss
126@import "~@ng-select/ng-select/themes/default.theme.css";
127// ... or
128@import "~@ng-select/ng-select/themes/material.theme.css";
129
130```
131
132
133### Step 4 (Optional): Configuration
134
135You can also set global configuration and localization messages by injecting NgSelectConfig service,
136typically in your root component, and customize the values of its properties in order to provide default values.
137
138```js
139 constructor(private config: NgSelectConfig) {
140 this.config.notFoundText = 'Custom not found';
141 this.config.appendTo = 'body';
142 // set the bindValue to global config when you use the same
143 // bindValue in most of the place.
144 // You can also override bindValue for the specified template
145 // by defining `bindValue` as property
146 // Eg : <ng-select bindValue="some-new-value"></ng-select>
147 this.config.bindValue = 'value';
148 }
149```
150
151### Usage
152Define options in your consuming component:
153```js
154@Component({...})
155export class ExampleComponent {
156
157 selectedCar: number;
158
159 cars = [
160 { id: 1, name: 'Volvo' },
161 { id: 2, name: 'Saab' },
162 { id: 3, name: 'Opel' },
163 { id: 4, name: 'Audi' },
164 ];
165}
166```
167In template use `ng-select` component with your options
168
169```html
170<!--Using ng-option and for loop-->
171<ng-select [(ngModel)]="selectedCar">
172 @for (car of cars; track car.id) {
173 <ng-option [value]="car.id">{{car.name}}</ng-option>
174 }
175</ng-select>
176
177<!--Using items input-->
178<ng-select [items]="cars"
179 bindLabel="name"
180 bindValue="id"
181 [(ngModel)]="selectedCar">
182</ng-select>
183```
184For more detailed examples see [Demo](https://ng-select.github.io/ng-select#/data-sources) page
185
186### SystemJS
187If you are using SystemJS, you should also adjust your configuration to point to the UMD bundle.
188
189In your systemjs config file, `map` needs to tell the System loader where to look for `ng-select`:
190```js
191map: {
192 '@ng-select/ng-select': 'node_modules/@ng-select/ng-select/bundles/ng-select.umd.js',
193}
194```
195
196## API
197### Inputs
198| Input | Type | Default | Required | Description |
199| ------------- | ------------- | ------------- | ------------- | ------------- |
200| [addTag] | `boolean \| ((term: string) => any \| Promise<any>)` | `false` | no | Allows to create custom options. |
201| addTagText | `string` | `Add item` | no | Set custom text when using tagging |
202| appearance | `string` | `underline` | no | Allows to select dropdown appearance. Set to `outline` to add border instead of underline (applies only to Material theme) |
203| appendTo | `string` | null | no | Append dropdown to body or any other element using css selector. For correct positioning `body` should have `position:relative` |
204| bufferAmount | `string` | null | no | Append dropdown to body or any other element using css selector. For correct positioning `body` should have `position:relative` |
205| bindValue | `string` | `-` | no | Object property to use for selected model. By default binds to whole object. |
206| bindLabel | `string` | `label` | no | Object property to use for label. Default `label` |
207| [closeOnSelect] | `boolean` | true | no | Whether to close the menu when a value is selected |
208| clearAllText | `string` | `Clear all` | no | Set custom text for clear all icon title |
209| [clearable] | `boolean` | `true` | no | Allow to clear selected value. Default `true`|
210| [clearOnBackspace] | `boolean` | `true` | no | Clear selected values one by one when clicking backspace. Default `true`|
211| [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. |
212| dropdownPosition | `bottom` \| `top` \| `auto` | `auto` | no | Set the dropdown position on open |
213| [groupBy] | `string` \| `Function` | null | no | Allow to group items by key or function expression |
214| [groupValue] | `(groupKey: string, children: any[]) => Object` | - | no | Function expression to provide group value |
215| [selectableGroup] | `boolean` | false | no | Allow to select group when groupBy is used |
216| [selectableGroupAsModel] | `boolean` | true | no | Indicates whether to select all children or group itself |
217| [items] | `Array<any>` | `[]` | yes | Items array |
218| [loading] | `boolean` | `-` | no | You can set the loading state from the outside (e.g. async items loading) |
219| loadingText | `string` | `Loading...` | no | Set custom text when for loading items |
220| labelForId | `string` | `-` | no | Id to associate control with label. |
221| [markFirst] | `boolean` | `true` | no | Marks first item as focused when opening/filtering. |
222| [isOpen] | `boolean` | `-` | no | Allows manual control of dropdown opening and closing. `true` - won't close. `false` - won't open. |
223| maxSelectedItems | `number` | none | no | When multiple = true, allows to set a limit number of selection. |
224| [hideSelected] | `boolean` | `false` | no | Allows to hide selected items. |
225| [multiple] | `boolean` | `false` | no | Allows to select multiple items. |
226| notFoundText | `string` | `No items found` | no | Set custom text when filter returns empty result |
227| placeholder | `string` | `-` | no | Placeholder text. |
228| [searchable] | `boolean` | `true` | no | Allow to search for value. Default `true`|
229| [readonly] | `boolean` | `false` | no | Set ng-select as readonly. Mostly used with reactive forms. |
230| [searchFn] | `(term: string, item: any) => boolean` | `null` | no | Allow to filter by custom search function |
231| [searchWhileComposing] | `boolean` | `true` | no | Whether items should be filtered while composition started |
232| [trackByFn] | `(item: any) => any` | `null` | no | Provide custom trackBy function |
233| [clearSearchOnAdd] | `boolean` | `true` | no | Clears search input when item is selected. Default `true`. Default `false` when **closeOnSelect** is `false` |
234| [deselectOnClick] | `boolean` | `false` | no | Deselects a selected item when it is clicked in the dropdown. Default `false`. Default `true` when **multiple** is `true` |
235| [editableSearchTerm] | `boolean` | `false` | no | Allow to edit search query if option selected. Default `false`. Works only if multiple is `false`. |
236| [selectOnTab] | `boolean` | `false` | no | Select marked dropdown item using tab. Default `false`|
237| [openOnEnter] | `boolean` | `true` | no | Open dropdown using enter. Default `true`|
238| [typeahead] | `Subject` | `-` | no | Custom autocomplete or advanced filter. |
239| [minTermLength] | `number` | `0` | no | Minimum term length to start a search. Should be used with `typeahead` |
240| typeToSearchText | `string` | `Type to search` | no | Set custom text when using Typeahead |
241| [virtualScroll] | `boolean` | false | no | Enable virtual scroll for better performance when rendering a lot of data |
242| [inputAttrs] | `{ [key: string]: string }` | `-` | no | Pass custom attributes to underlying `input` element |
243| [tabIndex] | `number` | `-` | no | Set tabindex on ng-select |
244| [preventToggleOnRightClick] | `boolean` | `false` | no | Prevent opening of ng-select on right mouse click |
245| [keyDownFn] | `($event: KeyboardEvent) => bool` | `true` | no | Provide custom keyDown function. Executed before default handler. Return false to suppress execution of default key down handlers |
246
247### Outputs
248
249| Output | Description |
250| ------------- | ------------- |
251| (add) | Fired when item is added while `[multiple]="true"`. Outputs added item |
252| (blur) | Fired on select blur |
253| (change) | Fired on model change. Outputs whole model |
254| (close) | Fired on select dropdown close |
255| (clear) | Fired on clear icon click |
256| (focus) | Fired on select focus |
257| (search) | Fired while typing search term. Outputs search term with filtered items |
258| (open) | Fired on select dropdown open |
259| (remove) | Fired when item is removed while `[multiple]="true"` |
260| (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. |
261| (scrollToEnd) | Fired when scrolled to the end of items. Can be used for loading more items in chunks. |
262
263
264### Methods
265 Name | Description |
266| ------------- | ------------- |
267| open | Opens the select dropdown panel |
268| close | Closes the select dropdown panel |
269| focus | Focuses the select element |
270| blur | Blurs the select element |
271
272### Other
273 Name | Type | Description |
274| ------------- | ------------- | ------------- |
275| [ngOptionHighlight] | directive | Highlights search term in option. Accepts search term. Should be used on option element. [README](https://github.com/ng-select/ng-select/blob/master/src/ng-option-highlight/README.md) |
276| NgSelectConfig | configuration | Configuration provider for the NgSelect component. You can inject this service and provide application wide configuration. |
277| SELECTION_MODEL_FACTORY | service | DI token for SelectionModel implementation. You can provide custom implementation changing selection behaviour. |
278
279## Custom selection logic
280Ng-select allows to provide custom selection implementation using `SELECTION_MODEL_FACTORY`. To override [default](https://github.com/ng-select/ng-select/blob/master/src/ng-select/lib/selection-model.ts) logic provide your factory method in your angular module.
281
282```javascript
283// app.module.ts
284providers: [
285 { provide: SELECTION_MODEL_FACTORY, useValue: <SelectionModelFactory>CustomSelectionFactory }
286]
287
288// selection-model.ts
289export function CustomSelectionFactory() {
290 return new CustomSelectionModel();
291}
292
293export class CustomSelectionModel implements SelectionModel {
294 ...
295}
296```
297
298## Change Detection
299Ng-select component implements `OnPush` change detection which means the dirty checking checks for immutable
300data types. That means if you do object mutations like:
301
302```javascript
303this.items.push({id: 1, name: 'New item'})
304```
305
306Component will not detect a change. Instead you need to do:
307
308```javascript
309this.items = [...this.items, {id: 1, name: 'New item'}];
310```
311
312This will cause the component to detect the change and update. Some might have concerns that
313this is a pricey operation, however, it is much more performant than running `ngDoCheck` and
314constantly diffing the array.
315
316## Custom styles
317If 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.
318
319```html
320<ng-select class="custom"></ng-select>
321```
322
323```css
324.ng-select.custom {
325 border:0px;
326 min-height: 0px;
327 border-radius: 0;
328}
329.ng-select.custom .ng-select-container {
330 min-height: 0px;
331 border-radius: 0;
332}
333```
334
335If 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.
336
337```css
338.ng-select.custom ::ng-deep .ng-select-container {
339 min-height: 0px;
340 border-radius: 0;
341}
342```
343WARNING: Keep in mind that ng-deep is deprecated and there is no alternative to it yet. See [Here](https://github.com/angular/angular/issues/17867).
344
345### Validation state
346By 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
347
348```css
349ng-select.ng-invalid.ng-touched .ng-select-container {
350 border-color: #dc3545;
351 box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px #fde6e8;
352}
353```
354
355## Contributing
356
357Contributions are welcome. You can start by looking at [issues](https://github.com/ng-select/ng-select/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) with label *Help wanted* or creating new Issue with proposal or bug report.
358Note that we are using https://conventionalcommits.org/ commits format.
359
360## Development
361
362Perform the _clone-to-launch_ steps with these terminal commands.
363
364### Run demo page in watch mode
365```
366git clone https://github.com/ng-select/ng-select
367cd ng-select
368yarn
369yarn run start
370```
371### Testing
372```
373yarn run test
374or
375yarn run test:watch
376```
377
378### Release
379
380To release to npm just run `./release.sh`, of course if you have permissions ;)
381
382## Inspiration
383This component is inspired by [React select](https://github.com/JedWatson/react-select) and [Virtual scroll](https://github.com/rintoj/angular2-virtual-scroll). Check theirs amazing work and components :)
384