6.0.0 • Published 1 year ago

@anderstornkvist/ng-select v6.0.0

Weekly downloads
6
License
MIT
Repository
github
Last release
1 year ago

npm version Build Status Coverage Status gzip bundle size

Angular ng-select (fork) - Lightweight all in one UI Select, Multiselect and Autocomplete

See Demos or try in Stackblitz


Versions

Angularng-select
v6.xv2.x
v5.xv1.x

Table of contents

Features

  • Custom binding to property or object
  • Custom option, label, header and footer templates
  • Virtual Scroll support with large data sets (>5000 items).
  • Infinite scroll
  • Keyboard navigation
  • Multiselect
  • Flexible autocomplete with client/server filtering
  • Custom search
  • Custom tags
  • Append to
  • Group items
  • Output events
  • Accessibility
  • Good base functionality test coverage
  • Themes

Warning

Library is under active development and may have API breaking changes for subsequent major versions after 1.0.0.

Getting started

Step 1: Install ng-select:

NPM

npm install --save @ng-select/ng-select

YARN

yarn add @ng-select/ng-select

Step 2: Import the NgSelectModule and angular FormsModule module:

import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent],
  imports: [NgSelectModule, FormsModule],
  bootstrap: [AppComponent]
})
export class AppModule {}

Step 3: Include a theme:

To 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).

@import "~@ng-select/ng-select/themes/default.theme.css";
// ... or 
@import "~@ng-select/ng-select/themes/material.theme.css";

Step 4 (Optional): Configuration

You can also set global configuration and localization messages by injecting NgSelectConfig service, typically in your root component, and customize the values of its properties in order to provide default values.

  constructor(private config: NgSelectConfig) {
      this.config.notFoundText = 'Custom not found';
  }

SystemJS

If you are using SystemJS, you should also adjust your configuration to point to the UMD bundle.

In your systemjs config file, map needs to tell the System loader where to look for ng-select:

map: {
  '@ng-select/ng-select': 'node_modules/@ng-select/ng-select/bundles/ng-select.umd.js',
}

API

Inputs

InputTypeDefaultRequiredDescription
addTagboolean \| ((term: string) => any \| Promise<any>)falsenoAllows to create custom options.
addTagAlwaysboolean |false| no | Allows to create custom options even when loading items or match exists. Defaultfalse`. Use together with addTag if you want to use custom add function.
addTagTextstringAdd itemnoSet custom text when using tagging
appendTostringnullnoAppend dropdown to body or any other element using css selector. For correct positioning body should have position:relative
bindValuestring-noObject property to use for selected model. By default binds to whole object.
bindLabelstringlabelnoObject property to use for label. Default label
closeOnSelectbooleantruenoWhether to close the menu when a value is selected
clearAllTextstringClear allnoSet custom text for clear all icon title
clearablebooleantruenoAllow to clear selected value. Default true
compareWith(a: any, b: any) => boolean(a, b) => a === bnoA 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.
dropdownPositionbottom | top | autoautonoSet the dropdown position on open
excludeGroupsFromDefaultSelectionbooleanfalsenoExclude group from default selection when selectableGroup is true. Default false.
groupBystring | FunctionnullnoAllow to group items by key or function expression
groupValue(groupKey: string, cildren: any[]) => Object-noFunction expression to provide group value
selectableGroupbooleanfalsenoAllow to select group when groupBy is used
selectableGroupAsModelbooleantruenoIndicates whether to select all children or group itself
itemsArray<any>[]yesItems array
loadingboolean-noYou can set the loading state from the outside (e.g. async items loading)
loadingTextstringLoading...noSet custom text when for loading items
labelForIdstring-noId to associate control with label.
markFirstbooleantruenoMarks first item as focused when opening/filtering.
isOpenboolean-noAllows manual control of dropdown opening and closing. True - won't close. False - won't open.
maxSelectedItemsnumbernonenoWhen multiple = true, allows to set a limit number of selection.
hideSelectedbooleanfalsenoAllows to hide selected items.
multiplebooleanfalsenoAllows to select multiple items.
notFoundTextstringNo items foundnoSet custom text when filter returns empty result
placeholderstring-noPlaceholder text.
searchablebooleantruenoAllow to search for value. Default true
searchFn(term: string, item: any) => booleannullnoAllow to filter by custom search function
clearSearchOnAddbooleantruenoClears search input when item is selected. Default true. Default false when closeOnSelect is false
selectOnTabbooleanfalsenoSelect marked dropdown item using tab. Default false
openOnEnterbooleantruenoOpen dropdown using enter. Default true
typeaheadSubject-noCustom autocomplete or advanced filter.
typeToSearchTextstringType to searchnoSet custom text when using Typeahead
virtualScrollbooleanfalsenoEnable virtual scroll for better performance when rendering a lot of data

Outputs

OutputDescription
(add)Fired when item is added while [multiple]="true". Outputs added item
(blur)Fired on select blur
(change)Fired on model change. Outputs whole model
(close)Fired on select dropdown close
(clear)Fired on clear icon click
(focus)Fired on select focus
(search)Fired while typing search term
(open)Fired on select dropdown open
(remove)Fired when item is removed while [multiple]="true"
(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.
(scrollToEnd)Fired when scrolled to the end of items. Can be used for loading more items in chunks.

Methods

NameDescription
openOpens the select dropdown panel
closeCloses the select dropdown panel
focusFocuses the select element

Other

NameTypeDescription
ngOptionHighlightdirectiveHighlights search term in option. Accepts search term. Should be used on option element.
NgSelectConfigconfigurationConfiguration provider for the NgSelect component. You can inject this service and provide application wide configuration.
SELECTION_MODEL_FACTORYserviceDI token for SelectionModel implementation. You can provide custom implementation changing selection behaviour.

Change Detection

Ng-select component implements OnPush change detection which means the dirty checking checks for immutable data types. That means if you do object mutations like:

this.items.push({id: 1, name: 'New item'})

Component will not detect a change. Instead you need to do:

this.items = [...this.items, {id: 1, name: 'New item'}];

This will cause the component to detect the change and update. Some might have concerns that this is a pricey operation, however, it is much more performant than running ngDoCheck and constantly diffing the array.

Custom styles

If 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.

<ng-select class="custom"></ng-select>
.ng-select.custom {
    border:0px;
    min-height: 0px;
    border-radius: 0;
}
.ng-select.custom .ng-select-container  {            
    min-height: 0px;
    border-radius: 0;
}

If you are using ViewEncapsulation, your should use special ::ng-deep selector which will prevent scoping for nested selectors.

.ng-select.custom ::ng-deep .ng-select-container  {            
    min-height: 0px;
    border-radius: 0;
}

WARNING: Keep in mind that ng-deep is deprecated and there is no alternative to it yet. See https://github.com/angular/angular/issues/17867.

Validation state

By 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

ng-select.ng-invalid.ng-touched .ng-select-container {
    border-color: #dc3545;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px #fde6e8;
}

Contributing

Contributions are welcome. You can start by looking at issues with label Help wanted or creating new Issue with proposal or bug report. Note that we are using https://conventionalcommits.org/ commits format.

Development

Perform the clone-to-launch steps with these terminal commands.

Run demo page in watch mode

git clone https://github.com/ng-select/ng-select
cd ng-select
yarn
yarn run start

Testing

yarn run test
or
yarn run test:watch

Release

To release to npm just run ./release.sh, of course if you have permissions ;)

Inspiration

This component is inspired by React select and Virtual scroll. Check theirs amazing work and components :)

Just a fork

This is just a fork of the original ng-select module with some additions. See Github for information about which additions.

6.0.0

1 year ago

0.1.1

4 years ago

0.1.0

4 years ago