Angular NgbTypeahead

Manu picture Manu · Aug 12, 2017 · Viewed 11.7k times · Source

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

Everything working fine, But I want Multiple Values on one single text box. As that field is a from group, once one value selected, it can allow next one, without remove previous one.

Answer

pkozlowski.opensource picture pkozlowski.opensource · Aug 12, 2017

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