Choosing multiple values in ng-bootstrap Typeahead
Asked Answered
O

1

6

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.

Oophorectomy answered 12/8, 2017 at 7:52 Comment(0)
R
8

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

Recreate answered 12/8, 2017 at 10:2 Comment(1)
Hi, instead of, to get states from a static array , want from back end,ex: firebase. can help how to get async observable data for NgbTypeaheadOophorectomy

© 2022 - 2024 — McMap. All rights reserved.