Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

⭐ Native angular select component

License

NotificationsYou must be signed in to change notification settings

ng-select/ng-select

Repository files navigation

npm versionCoverage Statusgzip bundle sizeng-select channel on discord

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

SeeDemo page.


Versions

Warning: Do not use versions 15.2.0, 16.0.0, 17.0.0, 18.0.0, 19.0.0, 20.0.0 as they contain unresolved issues

Angularng-select
>=20.0.0 <21.0.0<=15.1.3, >=20.0.1
>=19.0.0 <20.0.0v14.x
>=18.0.0 <19.0.0v13.x
>=17.0.0 <18.0.0v12.x
>=16.0.0 <17.0.0v11.x
>=15.0.0 <16.0.0v10.x
>=14.0.0 <15.0.0v9.x
>=13.0.0 <14.0.0v8.x
>=12.0.0 <13.0.0v7.x
>=11.0.0 <12.0.0v6.x
>=10.0.0 <11.0.0v5.x
>=9.0.0 <10.0.0v4.x
>=8.0.0 <9.0.0v3.x
>=6.0.0 <8.0.0v2.x
v5.x.xv1.x

Browser Support

ng-select supports all browsers supported by Angular. For current list, seehttps://angular.io/guide/browser-support#browser-support. This includes the following specific versions:

Chrome2 most recent versionsFirefoxlatest and extended support release (ESR)Edge2 most recent major versionsSafari2 most recent major versionsiOS2 most recent major versionsAndroid2 most recent major versions

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: Installng-select:

NPM

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

YARN

yarn add @ng-select/ng-select

Step 2:

Standalone: Import NgSelectComponent and other necessary directives directly:

import{NgLabelTemplateDirective,NgOptionTemplateDirective,NgSelectComponent}from'@ng-select/ng-select';import{FormsModule}from'@angular/forms';@Component({selector:'example',standalone:true,template:'./example.component.html',styleUrl:'./example.component.scss',imports:[NgLabelTemplateDirective,NgOptionTemplateDirective,NgSelectComponent,],})exportclassExampleComponent{}

NgModule: 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]})exportclassAppModule{}

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 yourstyles.scss or include it in.angular-cli.json (Angular v5 and below) orangular.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(privateconfig:NgSelectConfig){this.config.notFoundText='Custom not found';this.config.appendTo='body';// set the bindValue to global config when you use the same// bindValue in most of the place.// You can also override bindValue for the specified template// by defining `bindValue` as property// Eg : <ng-select bindValue="some-new-value"></ng-select>this.config.bindValue='value';}

Usage

Define options in your consuming component:

@Component({...})exportclassExampleComponent{selectedCar:number;cars=[{id:1,name:'Volvo'},{id:2,name:'Saab'},{id:3,name:'Opel'},{id:4,name:'Audi'},];}

In template useng-select component with your options

<!--Using ng-option and for loop--><ng-select[(ngModel)]="selectedCar">    @for (car of cars; track car.id) {<ng-option[value]="car.id">{{car.name}}</ng-option>    }</ng-select><!--Using items input--><ng-select[items]="cars"bindLabel="name"bindValue="id"[(ngModel)]="selectedCar"></ng-select>

For more detailed examples seeDemo page

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 forng-select:

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

API

Inputs

InputTypeDefaultRequiredDescription
[addTag]boolean | ((term: string) => any | Promise<any>)falsenoAllows to create custom options.
addTagTextstringAdd itemnoSet custom text when using tagging
appearancestringunderlinenoAllows to select dropdown appearance. Set tooutline to add border instead of underline (applies only to Material theme)
appendTostringnullnoAppend dropdown to body or any other element using css selector. For correct positioningbody should haveposition:relative
bufferAmountnumber4noUsed in virtual scrolling, thebufferAmount property controls the number of items preloaded in the background to ensure smoother and more seamless scrolling.
bindValuestring-noObject property to use for selected model. By default binds to whole object.
bindLabelstringlabelnoObject property to use for label. Defaultlabel
[closeOnSelect]booleantruenoWhether to close the menu when a value is selected
clearAllTextstringClear allnoSet custom text for clear all icon title
[clearable]booleantruenoAllow to clear selected value. Defaulttrue
[clearOnBackspace]booleantruenoClear selected values one by one when clicking backspace. Defaulttrue
[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
[fixedPlaceholder]booleanfalsenoSet placeholder visible even when an item is selected
[groupBy]string |FunctionnullnoAllow to group items by key or function expression
[groupValue](groupKey: string, children: any[]) => Object-noFunction expression to provide group value
[selectableGroup]booleanfalsenoAllow to select group when groupBy is used
[selectableGroupAsModel]booleantruenoIndicates whether to select all children or group itself
[items]Array<any>[]yesItems array
[loading]boolean-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.
[markFirst]booleantruenoMarks first item as focused when opening/filtering.
[isOpen]boolean-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.
[hideSelected]booleanfalsenoAllows to hide selected items.
[multiple]booleanfalsenoAllows to select multiple items.
notFoundTextstringNo items foundnoSet custom text when filter returns empty result
placeholderstring-noPlaceholder text.
[searchable]booleantruenoAllow to search for value. Defaulttrue
[readonly]booleanfalsenoSet ng-select as readonly. Mostly used with reactive forms.
[searchFn](term: string, item: any) => booleannullnoAllow to filter by custom search function
[searchWhileComposing]booleantruenoWhether items should be filtered while composition started
[trackByFn](item: any) => anynullnoProvide custom trackBy function
[clearSearchOnAdd]booleantruenoClears search input when item is selected. Defaulttrue. Defaultfalse whencloseOnSelect isfalse
[deselectOnClick]booleanfalsenoDeselects a selected item when it is clicked in the dropdown. Defaultfalse. Defaulttrue whenmultiple istrue
[editableSearchTerm]booleanfalsenoAllow to edit search query if option selected. Defaultfalse. Works only if multiple isfalse.
[selectOnTab]booleanfalsenoSelect marked dropdown item using tab. Defaultfalse
[tabFocusOnClearButton]booleantruenoControl tab navigation behavior for the clear button. Defaulttrue
[openOnEnter]booleantruenoOpen dropdown using enter. Defaulttrue
[typeahead]Subject-noCustom autocomplete or advanced filter.
[minTermLength]number0noMinimum term length to start a search. Should be used withtypeahead
typeToSearchTextstringType to searchnoSet custom text when using Typeahead
[virtualScroll]booleanfalsenoEnable virtual scroll for better performance when rendering a lot of data
[inputAttrs]{ [key: string]: string }-noPass custom attributes to underlyinginput element
[tabIndex]number-noSet tabindex on ng-select
[preventToggleOnRightClick]booleanfalsenoPrevent opening of ng-select on right mouse click
[keyDownFn]($event: KeyboardEvent) => booltruenoProvide custom keyDown function. Executed before default handler. Return false to suppress execution of default key down handlers

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. Outputs search term with filtered items
(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
blurBlurs the select element

Other

NameTypeDescription
[ngOptionHighlight]directiveHighlights search term in option. Accepts search term. Should be used on option element.README
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.

Custom selection logic

Ng-select allows to provide custom selection implementation usingSELECTION_MODEL_FACTORY. To overridedefault logic provide your factory method in your angular module.

// app.module.ts.tsproviders:[{provide:SELECTION_MODEL_FACTORY,useValue:<SelectionModelFactory>CustomSelectionFactory}]// selection-model.tsexportfunctionCustomSelectionFactory(){returnnewCustomSelectionModel();}exportclassCustomSelectionModelimplementsSelectionModel{    ...}

Change Detection

Ng-select component implementsOnPush change detection which means the dirty checking checks for immutabledata 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 thatthis is a pricey operation, however, it is much more performant than runningngDoCheck andconstantly 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 noViewEncapsulation or adding styles to global stylesheet. E.g.

<ng-selectclass="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 usingViewEncapsulation, 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.

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

Validation state

By default when you use reactive forms validators or template driven forms validators css classng-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: inset01px1pxrgba(0,0,0,0.075),0003px#fde6e8;}

Contributing

Contributions are welcome. You can start by looking atissues with labelHelp wanted or creating new Issue with proposal or bug report.Note that we are usinghttps://conventionalcommits.org/ commits format.

Development

Perform theclone-to-launch steps with these terminal commands.

Run demo page in watch mode

git clone https://github.com/ng-select/ng-selectcd ng-selectyarnyarn run start

Testing

yarn run testoryarn run test:watch

Release

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

Inspiration

This component is inspired byReact select andVirtual scroll. Check theirs amazing work and components :)


[8]ページ先頭

©2009-2025 Movatter.jp