UNPKG

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