Adding the Multiselect feature to an Angular2 Autocomplete

Angular2 Multi Selection Autocomplete
Angular2 Multi Selection Autocomplete

After I wrote the tutorial on how to create an angular2 autocomplete, lots of people have been asking me to add the multiselect feature to it, that’s the reason why I decided to write this one. I’m going to continue from where I stopped, so make sure you followed and understood every step from the previous tutorial before you proceed.

The first thing we have to do is to create a variable called selected, it’s just an array we’re going to use to store all the items selected by the user.

public selected = [];

Now let’s change a little bit the select() function, instead of assigning the item to the this.query variable we’re going to add it to the selected array and clean the this.query. This is the modification that will make the multiple selection possible. Here’s the code after the modification:

select(item){
    this.selected.push(item);
    this.query = '';
    this.filteredList = [];
}

We also need a way to remove items from the array, I’m going to create a function called remove (obviously), here’s the code:

remove(item){
    this.selected.splice(this.selected.indexOf(item),1);
}

This is a really straightforward function, it just receives an item and uses the splice() function to remove it from the array.

The template will also suffer some changes:

<div class="container" >
    <div class="input-field col s12">
      <input id="country" type="text" class="validate filter-input" [(ngModel)]=query (keyup)=filter()>
      <label for="country">Country</label>
    </div>
    <div class="suggestions" *ngIf="filteredList.length > 0">
        <ul *ngFor="#item of filteredList" >
            <li >
                <a (click)="select(item)">{{item}}</a>
            </li>
        </ul>
    </div>
    <div *ngFor="#item of selected">
        <div class="selected" >
            <span>{{item}}</span>
            <a (click)="remove(item)">x</a>
        </div>
    </div>
</div>

Notice that I’ve added another div bellow the suggestions list, that’s where the selected items will be displayed, also notice that each item will an ‘x’ that will call the remove function when clicked.

Lastly we have to do the styling, in this example I’ve used the following css to adjust how the selected items are displayed, but feel free to do as you like.

.selected{
	border:solid #4CAF50 1px;
	float:left; 
	margin:2px;
	padding:2px 15px;
}
 
.selected a{
	cursor:pointer;
	font-weight:bold;
}

That’s it guys! With just a few changes we can now select multiple items with our autocomplete, just leave a comment if you have any doubts.

Recommended for you

Angular2 Forms Tutorial: Validating Required Fields Angular2 Form Validation In this tutorial I'll give you a simple example of how to validate a form with angular2. As you can see in the image, the example consists of a form with two required fields, the form can only be submitted if both fields are valid. I'm going to use bootstrap for styli...
Angular2: How to Sort a JSON Dataset by Field To be able to sort an array we don't need anything specific from angular2, it can be accomplished just by using regular javascript, more specifically, we have to use the function sort() from the Array object, let's see an example: someArray.sort(function(a, b){ if ( a.someField < b.someFi...
Angular2 Tutorial: Creating Awesome Animated Charts with Highcharts Highcharts with Angular2 Today I'm going to show you how you can add some really amazing animated charts to your Angular 2 application. We're going to use a very rich library called Highcharts, it provides a huge variety of charts that you can use on your app. Seriously, they probably have any t...
Tutorial: How to redirect in Angular2 In this tutorial I'm going to give you a very simple example of how to navigate between components on an Angular2 application, but before we begin there are some configurations we have to do. We're going to use 2 components in this example: Component1 and Component2, to be able to redirect and na...

15 comments on “Adding the Multiselect feature to an Angular2 Autocomplete

  1. mike

    how is it going to work on the initial load when you have selected items already?
    You wanted to update the selected items with existing selected list. this is not going to work. can you show some example or update this example for update.

  2. priya

    Thanks a lot for this post!!
    My multiselect is working as shown in demo.But i am facing one issue when list get displayed all below controls get shifted.I want it should behaviour like dropdown.
    so to solve above issue I change code as

      0"&gt;
     
     
                    {{item.Value}}

    But now I am not able to get selected value due to Datalist..

  3. Tushar

    Thank You for your efforts!!! Could you please suggest how to show the selected items in the same input box like you have in single select example?

  4. Alex

    Great articles! (this and the single autocomplete) I would love if you would like to do another article when the scenario is an autocomplete which handles an Array of Objects? Anyway, great job! Thanks.

  5. Hasan

    Hi,

    I am unable to show any element in my suggestion box other that the first one. Even though my filtered list has more than one element.

     
     0"&gt;
      filter() {
        if (this.query !== "") {
          this.filteredList = this.users.filter(function (el) {
            if(el["FirstName"].toLowerCase().search(this.query.toLowerCase()) &gt; -1 ||
              el["LastName"].toLowerCase().search(this.query.toLowerCase()) &gt; -1 ||
              el["Username"].toLowerCase().search(this.query.toLowerCase()) &gt; -1)
            {
              return true;
            }
          }.bind(this));
        } else {
          this.filteredList = [];
        }
        return false;
      }
     
      select(item) {
        this.query = item;
        this.filteredList = [];
      }
    // SAMPLE ARRAY FOR THE SAKE OF THIS EXAMPLE
      this.users = [
          {
            FirstName: 'Hasan',
            LastName: 'Jalal',
            Username: 'jalalh2'
          },
          {
            FirstName: 'Jasbir',
            LastName: 'Gill',
            Username: 'gill9'
          }
     
        ];

    Please help.

  6. Jestin

    I find this multi-select really easy to implement and very easy to understand. But, I would need some help with the placement of the selected elements. Is there a way I can place the selected div in the input box which shows the multi-select dropdown ?

    Any help appreciated. Thanks.

  7. Tasfir Hossain Suman

    Hello
    I am very new in angularjs i am trying to use this nice multiselect autocomplete but i can’t.
    Anyone can you give me a source code and is this javascript or typescript

  8. Amit Gupta

    Hi Leonardo,

    Thanks a lot for awesome autocomplete!

    I want to use multiple autocomplete for my project, I have already done it using copy and paste its function and changed its array name. Is there any other way to create multiple autocomplete on one page?

    I have to create one for the country and second for the industry.

    I really appreciate you.

    Thank you once again

Leave a Reply to Hasan Cancel reply

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

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>