UNPKG

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