@abolutpersonal/ng-select 中文文档教程

发布于 6年前 浏览 21 项目主页 更新于 3年前

npm version构建状态覆盖状态gzip bundle size

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

请参阅 演示 或尝试 Stackblitz


Versions

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

Table of contents

Features

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

Warning

库正在积极开发中,可能会对 1.0.0 之后的后续主要版本进行 API 中断更改。

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:

为了允许自定义和主题化,ng-select 包仅包含正确布局和定位所必需的通用样式。 要全面了解该控件,请在您的应用程序中包含其中一个主题。 如果您使用的是 Angular CLI,则可以将其添加到 styles.scss 或将其包含在 .angular-cli.json(Angular v5 及以下版本)或 < code>angular.json(Angular v6 起)。

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

Step 4 (Optional): Configuration

您还可以通过注入 NgSelectConfig 服务来设置全局配置和本地化消息, 通常在您的根组件中,并自定义其属性的值以提供默认值。

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

SystemJS

如果您使用的是 SystemJS,您还应该调整您的配置以指向 UMD 包。

在你的 systemjs 配置文件中,map 需要告诉系统加载器在哪里寻找 ng-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
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
[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. Default true
[clearOnBackspace]booleantruenoClear selected values one by one when clicking backspace. 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
[excludeGroupsFromDefaultSelection]booleanfalsenoExclude group from default selection when selectableGroup is true. Default false.
[groupBy]string | FunctionnullnoAllow to group items by key or function expression
[groupValue](groupKey: string, cildren: 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. Default true
[searchFn](term: string, item: any) => booleannullnoAllow to filter by custom search function
[clearSearchOnAdd]booleantruenoClears search input when item is selected. Default true. Default false when closeOnSelect is false
[selectOnTab]booleanfalsenoSelect marked dropdown item using tab. Default false
[openOnEnter]booleantruenoOpen dropdown using enter. Default true
[typeahead]Subject-noCustom autocomplete or advanced filter.
typeToSearchTextstringType to searchnoSet custom text when using Typeahead
[virtualScroll]booleanfalsenoEnable virtual scroll for better performance when rendering a lot of data
autoCorrectstringoffnoAllows control of the autocorrect attribute.
autoCapitalizestringoffnoAllows control of the autocapitalize attribute.

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

Other

NameTypeDescription
[ngOptionHighlight]directiveHighlights 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.
SELECTIONMODELFACTORYserviceDI token for SelectionModel implementation. You can provide custom implementation changing selection behaviour.

Change Detection

Ng-select 组件实现 OnPush 变化检测这意味着脏检查检查不可变 数据类型。 这意味着如果您执行对象突变,例如:

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

组件将不会检测到更改。 相反,您需要这样做:

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

这将使组件检测到更改和更新。 有些人可能会担心 这是一个昂贵的操作,但是,它比运行 ngDoCheck 和 不断区分数组。

Custom styles

如果您对默认样式不满意,您可以通过增加选择器特异性或创建您自己的主题轻松覆盖它们。 如果您不使用 ViewEncapsulation 或向全局样式表添加样式,这适用。 例如

<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;
}

,如果您正在使用 ViewEncapsulation,您应该使用特殊的 ::ng-deep 选择器,这将阻止嵌套选择器的作用域。

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

警告:请记住,ng-deep 已被弃用,目前还没有替代品。 请参阅此处

Validation state

默认情况下,当您使用反应式表单验证器或模板驱动的表单验证器时,CSS 类 ng-invalid 将应用于 ng-select。 您可以通过添加自定义 css 样式来显示错误状态

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

欢迎贡献。 您可以先查看 带有标签需要帮助 的问题 或创建新的带有提案或错误报告的问题。 请注意,我们使用的是 https://conventionalcommits.org/ 提交格式。

Development

使用这些终端命令执行clone-to-launch 步骤。

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

要发布到 npm 只需运行 ./release.sh,当然如果你有权限的话 ;)

Inspiration

这个组件的灵感来自 React 选择虚拟滚动。 检查他们惊人的工作和组件:)

npm versionBuild StatusCoverage Statusgzip bundle size

Angular ng-select - 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

  • [x] Custom binding to property or object
  • [x] Custom option, label, header and footer templates
  • [x] Virtual Scroll support with large data sets (>5000 items).
  • [x] Infinite scroll
  • [x] Keyboard navigation
  • [x] Multiselect
  • [x] Flexible autocomplete with client/server filtering
  • [x] Custom search
  • [x] Custom tags
  • [x] Append to
  • [x] Group items
  • [x] Output events
  • [x] Accessibility
  • [x] Good base functionality test coverage
  • [x] 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
[addTag]boolean | ((term: string) => any | Promise<any>)falsenoAllows to create custom options.
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
[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. Default true
[clearOnBackspace]booleantruenoClear selected values one by one when clicking backspace. 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
[excludeGroupsFromDefaultSelection]booleanfalsenoExclude group from default selection when selectableGroup is true. Default false.
[groupBy]string | FunctionnullnoAllow to group items by key or function expression
[groupValue](groupKey: string, cildren: 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. Default true
[searchFn](term: string, item: any) => booleannullnoAllow to filter by custom search function
[clearSearchOnAdd]booleantruenoClears search input when item is selected. Default true. Default false when closeOnSelect is false
[selectOnTab]booleanfalsenoSelect marked dropdown item using tab. Default false
[openOnEnter]booleantruenoOpen dropdown using enter. Default true
[typeahead]Subject-noCustom autocomplete or advanced filter.
typeToSearchTextstringType to searchnoSet custom text when using Typeahead
[virtualScroll]booleanfalsenoEnable virtual scroll for better performance when rendering a lot of data
autoCorrectstringoffnoAllows control of the autocorrect attribute.
autoCapitalizestringoffnoAllows control of the autocapitalize attribute.

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

Other

NameTypeDescription
[ngOptionHighlight]directiveHighlights 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.
SELECTIONMODELFACTORYserviceDI 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 Here.

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 :)

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文