Coder Social home page Coder Social logo

aitboudad / ng-select Goto Github PK

View Code? Open in Web Editor NEW

This project forked from ng-select/ng-select

0.0 2.0 0.0 16.25 MB

Angular ng-select - All in One UI Select, Multiselect and Autocomplete

Home Page: https://ng-select.github.io/ng-select/

License: MIT License

TypeScript 78.57% JavaScript 11.54% HTML 2.84% CSS 6.79% Shell 0.25%

ng-select's Introduction

npm version Build Status Coverage Status

Angular ng-select - All in One UI Select, Multiselect and Autocomplete

See Demos or try in Plunker

Table of contents

Features

  • Custom bindings to property or object
  • Custom option and label templates
  • Virtual Scroll support with large data sets (>5000 items).
  • Keyboard navigation
  • Correct keyboard events behaviour
  • Multiselect
  • Flexible autocomplete with client/server filtering
  • Custom tags

Warning

Library is under active development and may not work as expected until stable 1.0.0 release.

Getting started

After installing the above dependencies, install ng-select via:

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

Once installed you need to import our main module:

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

The only remaining part is to list the imported module in your application module.:

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

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

You can also configure global configuration and localization messages by using NgSelectModule.forRoot:

NgSelectModule.forRoot({notFoundText: 'Your custom not found text', typeToSearchText: 'Your custom type to search text'})

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',
}

Roadmap

  • Custom binding to property or object
  • Custom option and label templates
  • Virtual Scroll support with large data sets (>5000 items).
  • Filter data by display text
  • Filter data by custom filter function
  • Expose useful events like blur, change, focus, close, open ...
  • Correct keyboard events behaviour
  • Integration app generated with angular-cli
  • Good base functionality test coverage
  • Multiselect support
  • Autocomplete
  • Custom tags
  • Accessibility

API

Input Type Default Required Description
[items] Array [] yes Items array
bindLabel string label no Object property to use for label. Default label
bindValue string - no Object property to use for selected model. By default binds to whole object.
[clearable] boolean true no Allow to clear selected value. Default true
multiple boolean false no Allows to select multiple items.
[addTag] Function or boolean false no Using boolean simply adds tag with value as bindLabel. If you want custom properties add function which returns object.
placeholder string - no Placeholder text.
notFoundText string No items found no Set custom text when filter returns empty result
typeToSearchText string Type to search no Set custom text when using Typeahead
addTagText string Add item no Set custom text when using tagging
[typeahead] Subject - no Custom autocomplete or filter.
Output Description
(focus) Fired on select focus
(blur) Fired on select blur
(change) Fired on selected value change
(open) Fired on select dropdown open
(close) Fired on select dropdown close

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.push({id: 1, name: 'New item'})
this.items = [...this.items];

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.

Examples

Basic example

This example in Plunkr

@Component({
    selector: 'cities-page',
    template: `
        <label>City</label>
        <ng-select [items]="cities"
                   bindLabel="name"
                   bindValue="id"
                   placeholder="Select city"
                   [(ngModel)]="selectedCityId">
        </ng-select>
        <p>
            Selected city ID: {{selectedCityId}}
        </p>
    `
})
export class CitiesPageComponent {
    cities = [
        {id: 1, name: 'Vilnius'},
        {id: 2, name: 'Kaunas'},
        {id: 3, name: 'Pabradė'}
    ];
    selectedCityId: any;
}

Flexible autocomplete

This example in Plunkr

In case of autocomplete you can get full control by creating simple EventEmmiter and passing it as an input to ng-select. When you type text, ng-select will fire events to EventEmmiter to which you can subscribe and control bunch of things like debounce, http cancellation and so on.

@Component({
    selector: 'select-autocomplete',
    template: `
        <label>Search with autocomplete in Github accounts</label>
        <ng-select [items]="items"
                   bindLabel="login"
                   placeholder="Type to search"
                   [typeahead]="typeahead"
                   [(ngModel)]="githubAccount">
            <ng-template ng-option-tmp let-item="item">
                <img [src]="item.avatar_url" width="20px" height="20px"> {{item.login}}
            </ng-template>
        </ng-select>
        <p>
            Selected github account:
            <span *ngIf="githubAccount">
                <img [src]="githubAccount.avatar_url" width="20px" height="20px"> {{githubAccount.login}}
            </span>
        </p>
    `
})
export class SelectAutocompleteComponent {

    githubAccount: any;
    items = [];
    
    // event emmiter is just RxJs Subject
    typeahead = new EventEmitter<string>();

    constructor(private http: HttpClient) {
        this.typeahead
            .distinctUntilChanged()
            .debounceTime(200)
            .switchMap(term => this.loadGithubUsers(term))
            .subscribe(items => {
                this.items = items;
            }, (err) => {
                console.log(err);
                this.items = [];
            });
    }

    loadGithubUsers(term: string): Observable<any[]> {
        return this.http.get<any>(`https://api.github.com/search/users?q=${term}`).map(rsp => rsp.items);
    }
}

Custom display and option templates

This example in Plunkr

To customize look of input display or option item you can use ng-template with ng-label-tmp or ng-option-tmp directives applied to it.

import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import {NgSelectModule} from '@ng-select/ng-select';
import {HttpClient, HttpClientModule} from '@angular/common/http';

@Component({
    selector: 'select-custom-templates',
    template: `
        <label>Demo for ng-select with custom templates</label>
        <ng-select [items]="albums"
                   [(ngModel)]="selectedAlbumId"
                   bindLabel="title"
                   bindValue="id"
                   placeholder="Select album">
            <ng-template ng-label-tmp let-item="item">
               <b>({{item.id}})</b> {{item.title}}
            </ng-template>
            <ng-template ng-option-tmp let-item="item">
                <div>Title: {{item.title}}</div>
                <small><b>Id:</b> {{item.id}} | <b>UserId:</b> {{item.userId}}</small>
            </ng-template>
        </ng-select>
        <p>Selected album ID: {{selectedAlbumId || 'none'}}</p>
    `
})
export class SelectCustomTemplatesComponent {
    albums = [];
    selectedAlbumId = null;

    constructor(http: HttpClient) {
        http.get<any[]>('https://jsonplaceholder.typicode.com/albums').subscribe(albums => {
            this.albums = albums;
        });
    }
}

More demos

Visit demos for more examples.

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

Credits

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

ng-select's People

Contributors

andrea-spotsoftware avatar anjmao avatar noejon avatar varnastadeus avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.