Angular 10|9|8 NgSelect with Single/ Multiple Selection and Search Filter

In this tutorial, we will discuss an awesome Dropdown select UI component which is loaded with many useful features which makes it a great choice for Angular 10/9/8/7/6/5/4 project. Showing listings of data for user selection is generally shown to the user in Select drop-down HTML control. Which is a traditional and nice way to…

By.

min read

In this tutorial, we will discuss an awesome Dropdown select UI component which is loaded with many useful features which makes it a great choice for Angular 10/9/8/7/6/5/4 project.

Showing listings of data for user selection is generally shown to the user in Select drop-down HTML control. Which is a traditional and nice way to show a limited set of data for selection.

But what if we have dynamic data lists that can have thousands of rows to show? We can’t simply feed all data to UI DOMS as it may adversely affect page performance.

In such a case, we can use the ng-select component which not only lets users select single of multiple options but can also load data dynamically to act like a typeahead or autocomplete suggestions.

The ng-select is also preferred as there is no need for any other dependency like Bootstrap or Angular Material.

[lwptoc]

Let’s get to know how quickly to use it!

For making this tutorial simple we will first create a new Angular project in the latest version 8.

Create a new Angular project

Using Ng CLI tool we will create a new Angular project by running below command in terminal:

$ ng new ng-select-demo

Install & Configure ng-select

After creating an Angular project next we will install the ng-select page.

Step 1) Installation

Run the following command in terminal to install ng-select:

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

 

Step 2) Import in App Module

To use ng-select component, we need to import NgSelectModule & FormsModule in app.module.ts file:

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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

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

 

Step 3) Theming

Finally, add a theme to style our awesome ng-select component.

We already have three themes available to select from. Import any of the following in the style.css file:

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

 

<strong>@import "~@ng-select/ng-select/themes/ant.design.theme.css";</strong>

Now we are done with ng-select installation and configurations required to use anywhere in our application:

Using ng-select Component

To create a select component add the ng-select component as shown below:

    <ng-select [items]="items"
               bindLabel="name"
               placeholder="Select item"
               appendTo="body"
               multiple="true"
               [(ngModel)]="selected">
    </ng-select>

 

with component class content:

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  items = [
    {id: 1, name: 'Python'},
    {id: 2, name: 'Node Js'},
    {id: 3, name: 'Java'},
    {id: 4, name: 'PHP', disabled: true},
    {id: 5, name: 'Django'},
    {id: 6, name: 'Angular'},
    {id: 7, name: 'Vue'},
    {id: 8, name: 'ReactJs'},
  ];
  selected = [
    {id: 2, name: 'Node Js'},
    {id: 8, name: 'ReactJs'}
  ];
}

There are some required and optional properties:

  • items : Array or object of local or remote content to populate as select options.
  • bindLabel : The property of an object which we want to show as a label in a select box.
  • placeholder : Text shown to the user when nothing is selected.
  • appendTo : By default, the options wrapper is appended to the ng-select element but it can be added to other elements using this property.
  • multiple : Single or multiple options can be selected by setting true or false
  • searchable : Boolean; Enable or disable filter feature.
  • clearable : Boolean; Add or remove cross icon to clear selected value.
  • maxSelectedItems : When multiple is set to true we can limit maximum items available to select.
  • disabled : Enable or disable the select component.

 

Also, check Search by Multiple Keys in @ng-select Select Filter

 

Using ng-select with ng-options

We can also use ng-option element in ng-select to customize the view of options as shown below:

    <ng-select bindLabel="name"
                placeholder="Select item"
                appendTo="body"
                multiple="true"
                [searchable]="true" 
                [clearable]="true"
                [(ngModel)]="selected">
                <ng-option [value]="item.id" [disabled]="item.disabled" *ngFor="let item of items">
                    <img src="./assets/{{item.image}}" width="20px" height="20px"/>
                    {{item.name}}
                </ng-option>
    </ng-select>

 

In component, we will have selected variable as an array of id’s

export class AppComponent {
  items = [
    {id: 1, name: 'Python', image: 'python.jpg'},
    {id: 2, name: 'Node Js', image: 'nodejs.jpg'},
    {id: 3, name: 'Java', image: 'java.jpg'},
    {id: 4, name: 'PHP', image: 'php.jpg', disabled: true},
    {id: 5, name: 'Django', image: 'django.jpg'},
    {id: 6, name: 'Angular', image: 'angular.jpg'},
    {id: 7, name: 'Vue', image: 'vue.jpg'},
    {id: 8, name: 'ReactJs', image: 'reactjs.jpg'},
  ];
  selected = [ 2, 8 ];
}

Show Checkboxes with Select Options

Checkboxes can be shown with each item and also as group checkboxes by using selectableGroup & selectableGroupAsModel properties.

<ng-select
    [items]="people"
    [multiple]="true"
    bindLabel="name"
    groupBy="gender"
    [selectableGroup]="true"
    [selectableGroupAsModel]="false"
    [closeOnSelect]="false"
    bindValue="id"
    [(ngModel)]="selectedPeople">
    <ng-template ng-optgroup-tmp let-item="item" let-item$="item$" let-index="index">
        <input id="item-{{index}}" type="checkbox" [ngModel]="item$.selected"/> {{item.gender | uppercase}}
    </ng-template>
    <ng-template ng-option-tmp let-item="item" let-item$="item$" let-index="index">
        <input id="item-{{index}}" type="checkbox" [ngModel]="item$.selected"/> {{item.name}}
    </ng-template>
</ng-select>

Get Values on Change

To get values on selection change use (change) event binder

    <ng-select  
                #MyNgSelect            
                bindLabel="name"
                placeholder="Select item"
                appendTo="body"
                multiple="true"
                [searchable]="true" 
                [clearable]="true"
                [closeOnSelect]="false"
                [(ngModel)]="selected"
                (change)="getValues()">
                <ng-option [value]="item.id" [disabled]="item.disabled" *ngFor="let item of items">
                    <img src="./assets/{{item.image}}" width="20px" height="20px"/>
                    {{item.name}}
                </ng-option>
    </ng-select>
    <ng-select  
                #MyNgSelect            
                bindLabel="name"
                placeholder="Select item"
                appendTo="body"
                multiple="true"
                [searchable]="true" 
                [clearable]="true"
                [closeOnSelect]="false"
                [(ngModel)]="selected"
                (change)="getValues()">
                <ng-option [value]="item.id" [disabled]="item.disabled" *ngFor="let item of items">
                    <img src="./assets/{{item.image}}" width="20px" height="20px"/>
                    {{item.name}}
                </ng-option>
    </ng-select>
...
  getValues() {
    console.log(this.selected);
  }
...

Also check, @ng-select Validation, Multiselection, Custom Property Binding and Checkboxes

 

Output Event Binding

The event can be triggered on select box operations by using the following output property methods:

<ng-select placeholder="Select some items"
           [items]="items"
           [(ngModel)]="selectedItems"
           bindLabel="name"
           bindValue="id"
           [multiple]="true"
           (open)="onOpen()"
           (close)="onClose()"
           (focus)="onFocus($event)"
           (search)="onSearch($event)"
           (blur)="onBlur($event)"
           (clear)="onClear()"
           (add)="onAdd($event)"
           (scrollToEnd)="onScrollToEnd($event)"
           (remove)="onRemove($event)"
           (change)="onChange($event)">
</ng-select>
...
export class OutputEventsExampleComponent implements OnInit {

    selectedItems: any;
    items = [];

    events: Event[] = [];

    constructor(private dataService: DataService) {
        this.dataService.getPeople().subscribe(items => {
            this.items = items;
        });
    }

    ngOnInit() {
    }

    onChange($event) {
        this.events.push({ name: '(change)', value: $event });
    }

    onFocus($event: Event) {
        this.events.push({ name: '(focus)', value: $event });
    }

    onBlur($event: Event) {
        this.events.push({ name: '(blur)', value: $event });
    }

    onOpen() {
        this.events.push({ name: '(open)', value: null });
    }

    onClose() {
        this.events.push({ name: '(close)', value: null });
    }

    onAdd($event) {
        this.events.push({ name: '(add)', value: $event });
    }

    onRemove($event) {
        this.events.push({ name: '(remove)', value: $event });
    }

    onClear() {
        this.events.push({ name: '(clear)', value: null });
    }

    onScrollToEnd($event) {
        this.events.push({ name: '(scrollToEnd)', value: $event });
    }

    onSearch($event) {
        this.events.push({ name: '(search)', value: $event });
    }
}

 

Also, read enable Virtual Scroll in ng-select

 

Template-driven Validation on NgSelect

For simple form validation, just put ng-select in a form with template variable #myForm and (submit) method.

On ng-select add name and required property as shown below:

<form #myForm="ngForm" (submit)="submitForm()">
    <div class="overflow-box">
        <ng-select  
                    #MyNgSelect            
                    bindLabel="name"
                    placeholder="Select item"
                    [(ngModel)]="selected"
                    name="mySelectBox"
                    required
                    >
                    <ng-option [value]="item.id" [disabled]="item.disabled" *ngFor="let item of items">
                        <img src="./assets/{{item.image}}" width="20px" height="20px"/>
                        {{item.name}}
                    </ng-option>
        </ng-select>
    </div>
    <button type="submit">Submit</button>
</form>

 

In component class, we will get the template variable reference using @ViewChild() and check form’s validation in submitForm method:

export class AppComponent implements OnInit {

  @ViewChild('myForm', {static: false}) MyForm: NgForm;

  submitForm(){
    this.MyForm.form.markAllAsTouched();
  }

}

Also, add the following CSS style in styles.css at project root to highlight error on  ng-select:

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

 

So here we discussed the basic implementation on the ng-select module to quickly integrate into an Angular project. Check out more examples and options here.

11 responses to “Angular 10|9|8 NgSelect with Single/ Multiple Selection and Search Filter”

  1. ALEX VILLATORO Avatar
    ALEX VILLATORO

    good article, thanks for sharing.

    will there be a way to remove the duplicate keys?

    I have a service that returns data to me and has duplicate values, will there be any filtering in this component that can remove duplicate data?

    1. Jolly.exe Avatar
      Jolly.exe

      You need to filter out dups before pushing them into NgSelect, I think this is what you are looking for 🙂
      https://www.freakyjolly.com/remove-duplicates-from-array-javascript-typescript-es6/

Leave a Reply

Your email address will not be published. Required fields are marked *