Multi Select Dropdown In Angular

Introduction

In this article, we are going to implement a multi-select dropdown in Angular applications. We will start from scratch to implement a multi-select dropdown.

In this article,

  • Create a new angular app
  • Install package
  • Implement Multi-select dropdown
  • Pass default selected value
  • Other Settings
  • Callback Methods

Create New Angular APP

For creating a new angular application, run the following command in your command prompt or terminal.

ng new <YourProjectName>

After running this command, angular CLI asks you for some settings like Do you want to enforce stricter type checking and stricter bundle budgets in the workspace? , Would you like to add Angular routing? and Which stylesheet format would you like to use? Give answer as per your preferences.

Installing package

Step 1

  1. For using multi-select dropdown here we use a package ng-multiselect-dropdown.
  2. Install this package in your project by the following command.
    npm i ng-multiselect-dropdown

Step 2

After successfully installing the package now we need to add this module in our app.module file. Add NgMultiSelectDropDownModule.forRoot() in your import array of app module file.

Implement Multi-select dropdown

Step 1

Create an array of items that you want to show in a dropdown in your .ts file. With your array, you have to define a list of settings used in this multi-select dropdown. To create both arrays as shown in the below code.

import { Component } from '@angular/core';
import { IDropdownSettings, } from 'ng-multiselect-dropdown';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dropdownList = [];  
  dropdownSettings:IDropdownSettings={};
  ngOnInit() {
    this.dropdownList = [
      { item_id: 1, item_text: 'Item1' },
      { item_id: 2, item_text: 'Item2' },
      { item_id: 3, item_text: 'Item3' },
      { item_id: 4, item_text: 'Item4' },
      { item_id: 5, item_text: 'Item5' }
    ];
    this.dropdownSettings = {     
      idField: 'item_id',
      textField: 'item_text',     
    };
  }
}

Step 2

Create a dropdown in your component.html file as shown in the below code. Here we pass our item array in data attribute and settings in settings attributes. As you saw in the above code in the setting list we pass the id field and the text field which defines that from our data array we want to use item_id as an ID field and item_text as a text field.

<div style="width:50%">
    <ng-multiselect-dropdown
        [settings]="dropdownSettings"
        [data]="dropdownList">
    </ng-multiselect-dropdown>
</div>

Output

Pass default selected value

Step 1

For passing default selection, we need to add this multi-select dropdown in the form. For that first, add FormsModule, ReactiveFormsModule in your import array of the app module files.

Step 2

Create a new form group and select list item array as shown below code.

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { IDropdownSettings, } from 'ng-multiselect-dropdown';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dropdownList = [];  
  selectedItems=[];
  dropdownSettings:IDropdownSettings={};
  dropDownForm:FormGroup;
  constructor(private fb: FormBuilder) {}
  ngOnInit() {
    this.dropdownList = [
      { item_id: 1, item_text: 'Item1' },
      { item_id: 2, item_text: 'Item2' },
      { item_id: 3, item_text: 'Item3' },
      { item_id: 4, item_text: 'Item4' },
      { item_id: 5, item_text: 'Item5' }
    ];
    this.dropdownSettings = {     
      idField: 'item_id',
      textField: 'item_text',     
    };
    this.selectedItems = [
      { item_id: 3, item_text: 'Item3'  },
      { item_id: 4,item_text: 'Item4' }
    ];
    this.dropDownForm = this.fb.group({
      myItems: [this.selectedItems]
  }); 
  }
}

Step 3

Add form group in your component file and add form control name as same as you gave in your form builder as shown in below code.

<div style="width:50%">
  <form [formGroup]="dropDownForm">
    <ng-multiselect-dropdown
       [settings]="dropdownSettings"
       [data]="dropdownList"
       formControlName="myItems">
    </ng-multiselect-dropdown>
  </form>
</div>

Output

Other Settings
 

Show hide select all

You can also modify that whether you want to show, select all checkboxes or not. For that, you need to add a property in your setting array. Add enableCheckAll:false to hide select all checkbox. By default it is true if you remove this property then you see select all checkbox.

this.dropdownSettings = {
    idField: 'item_id',
    textField: 'item_text',
    enableCheckAll: false,
};

Output

Change text of select all/ unselect all checkbox

You can also change the text of the select all and unselect all checkbox. For that, you need to add these two properties in your settings array, selectAllText, and unSelectAllText. Pass your desire string in these properties as shown below code.

this.dropdownSettings = {
    idField: 'item_id',
    textField: 'item_text',
    enableCheckAll: true,
    selectAllText: "Select All Items From List",
    unSelectAllText: "UnSelect All Items From List",
};

Output

Add place holder

Whenever you see a dropdown list you see a placeholder that shows some message like select city, select your state, or just simply select. In ng multi-select dropdown you can also add place holder like that. For showing placeholder in your dropdown, add [placeholder]="'Select Your Item'" in ng-multiselect-dropdown in your component file as shown in the below code.

<ng-multiselect-dropdown
    [placeholder]="'Select Your Item'"
    [settings]="dropdownSettings"
    [data]="dropdownList"
    formControlName="myItems">
</ng-multiselect-dropdown>

Output

No Data Placeholder

For some reason when you call dynamic data from API and you get nothing to show then you have to tell the user that there is no data or something like that. For showing this type of message you need to add noDataAvailablePlaceholderText in your setting array. Add like this noDataAvailablePlaceholderText:"There is no item available to show".

this.dropdownSettings = {
    idField: 'item_id',
    textField: 'item_text',
    noDataAvailablePlaceholderText: "There is no item availabale to show"
};

Output

Add search filter

Ng-multiselect-dropdown by default gave search filter for enabling this search filter you have to add a new setting in your settings array. Change your array as shown below.

this.dropdownSettings = {
    idField: 'item_id',
    textField: 'item_text',
    allowSearchFilter: true
};

Output

Callback Methods

  • onSelect - Return the selected item when an item is checked. Example : (onSelect)="onItemSelect($event)"
  • onSelectAll - Return the all items. Example : (onSelectAll)="onSelectAll($event)".
  • onDeSelect - Return the unselected item when an item is unchecked. Example : (onDeSelect)="onItemDeSelect($event)"
  • onFilterChange - Return the key press. Example : (onFilterChange)="onFilterChange($event)"
  • onDropDownClose- Example : (onDropDownClose)="onDropDownClose()"

Here are some example of callback methods.

onItemSelect(item: any) {
    console.log('onItemSelect', item);
}
onItemDeSelect(item: any) {
    console.log('onItemDeSelect', item);
}
onSelectAll(items: any) {
    console.log('onSelectAll', items);
}
onUnSelectAll() {
    console.log('onUnSelectAll fires');
}
<ng-multiselect-dropdown
    [placeholder]="'Select Your Item'"
    [settings]="dropdownSettings"
    [data]="dropdownList"
    formControlName="myItems"        
    (onSelect)="onItemSelect($event)"
    (onSelectAll)="onSelectAll($event)"
    (onDeSelect)="onItemDeSelect($event)"
    (onDeSelectAll)="onUnSelectAll()">
</ng-multiselect-dropdown>

Output

Conclusion

I hope you like this article. If you find it helpful, kindly share with your friends and like this article. If you have any doubt feel free to ask in the comment section. Thank you.