Search code examples
angularangular-bootstrapng-bootstrapangular-ui-typeahead

Choosing multiple values in ng-bootstrap Typeahead


I am using typeahead from Angular ng-bootstrap - https://ng-bootstrap.github.io/#/components/typeahead/examples

Everything is working fine, but I want multiple values on one single text box.

As that field is a form group, once one value is selected, it should can allow next one, without removing previous one.


Solution

  • You can build a custom multi-value select box on top of ng-bootstrap typeahead quite easily. The "trick" is to prevent selection of an item (so it is not bound to the model as a single value) and push it to a collection instead. Very easy to achieve while listening to the selectItem event, ex.: (selectItem)="selected($event)":

    selected($e) {
      $e.preventDefault();
      this.selectedItems.push($e.item);
      this.inputEl.nativeElement.value = '';
    }
    

    As soon as you've got your selected items in a collection, you can display it before the input field:

    <div class="form-control">
      <span class="btn btn-primary btn-sm selected" *ngFor="let item of selectedItems">
        {{item}}
        <span class="close-selected" (click)="close(item)">&nbsp;x</span>
      </span>
      <input #input type="text" class="input" [ngbTypeahead]="search" (selectItem)="selected($event)" autofocus placeholder="Select something..."/>
    </div>
    

    Sprinkle a bit of custom CSS and you've got a multi-select working! Here is a complete example in a plunker: https://plnkr.co/edit/sZNw1lO2y3ZZR0GxLyjD?p=preview

    Also see detailed discussion in https://github.com/ng-bootstrap/ng-bootstrap/issues/532