UNPKG

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