UNPKG

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