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:

    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:


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 class="suggestions" *ngIf="filteredList.length > 0">
        <ul *ngFor="#item of filteredList" >
            <li >
                <a (click)="select(item)">{{item}}</a>
    <div *ngFor="#item of selected">
        <div class="selected" >
            <a (click)="remove(item)">x</a>

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.

	border:solid #4CAF50 1px;
	padding:2px 15px;
.selected a{

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.