Select a value from typeahead shows Objec object
Asked Answered
A

3

7

I am working on Single Page Application and using Angular-TypeAhead when i write something in textbox it shows me suggestions but when i select the suggestion then the values of Textbox become Object object instead of name

here is my HTML Markup

<div class="bs-example" style="padding-bottom: 24px;" append-source>
    <form class="form-inline" role="form">
      <div class="form-group">
        <label><i class="fa fa-globe"></i> State</label>
        <input type="text" class="form-control" ng-model="selectedState" ng-options="state.FirstName for state in states" placeholder="Enter state" bs-typeahead>
      </div>
    </form>
  </div>

and here is my AngularJS code

var app = angular.module('mgcrea.ngStrapDocs', ['ngAnimate', 'ngSanitize', 'mgcrea.ngStrap'])

        .controller('TypeaheadDemoCtrl', function ($scope, $templateCache, $http) {

            $scope.selectedState = '';

            $http.get('/api/servicesapi/GetAllClients')
            .then(
                function (result) {
                    //success
                    $scope.states = result.data;
                },
                function () {
                    //error
                });

        });

see the images here

enter image description here enter image description here

Acetylate answered 21/3, 2014 at 11:48 Comment(4)
What if you get if you do console.log($scope.states) ???Vivavivace
it shows the object which is returned which contain Id,FirstName,Email etcAcetylate
you need to change your ng-model to be the property of that object that you want there. so, something like: ng-model="selectedState.name" or something like that.Rimbaud
I have the same problem but in angular 4Leonidaleonidas
G
6

Change ng-options="state.FirstName for state in states" to ng-options="state as state.FirstName for state in states"

Gulp answered 12/8, 2014 at 22:10 Comment(0)
L
2

This is the solution in Angular 4 and not angularJS

I added [inputFormatter]="formatMatches" to format the input (ngmodel) and [resultFormatter]="formatMatches" to format the data displayed

<input id="typeahead-format" type="text" [(ngModel)]="clickedItem" 
    name="profile" (selectItem)="selectedItem($event)"
   [resultFormatter]="formatter" [inputFormatter]="formatter"
   [ngbTypeahead]="search" #instance="ngbTypeahead"/>

and the formatter function is like this:

formatter = (x: { label: string }) => x.label;

x: is the object

Leonidaleonidas answered 27/4, 2018 at 9:35 Comment(0)
B
0

For anyone using angular bootstrap and finding the same issue, I spent too long on this.

Essentially you need to consider the model to be a string on the way out and then converted to a string from the complex model returned from the api call.

You then need to hook into the OnSelect method to extract the complex object and store this (or the unique id form the object) in a separate variable. It is right then in the documents, but it is not given much prominence given that you would normally want a key / value pair from a typeahead. Not just a string.

https://valor-software.com/ngx-bootstrap/#/typeahead#on-select

Here is a code snippet from a typeahead which works fine, to set the search as the [name] value from a complex object and the selectedObject to be the whole item.

  <pre class="card card-block card-header">Search: {{ search | json }}</pre>
      <pre class="card card-block card-header">Selected: {{ selectedOption | json }}</pre>

      <ng-template #customItemTemplate let-model="item" let-index="index">
        <div>
          <p>This is: {{ model.name }} Number: {{ model.id }} Index: {{ index }}</p>
          <p>Some secondary information about {{ model.name }}</p>
        </div>
      </ng-template>

      <input [(ngModel)]="search"
             [typeahead]="suggestions$"
             typeaheadOptionField="name"
             (typeaheadOnSelect)="onSelect($event)"
             [typeaheadAsync]="true"
             typeaheadWaitMs="500"
             [typeaheadMinLength]="3"
             [typeaheadItemTemplate]="customItemTemplate"
             class="form-control"
             placeholder="Enter a street name">

             <div class="alert alert-danger" role="alert" *ngIf="errorMessage">
               {{ errorMessage }}
             </div>

then in my component I have

  ngOnInit(): void {
    this.suggestions$ = new Observable((observer: Observer<string>) => {
      observer.next(this.search);
    }).pipe(
      switchMap((query: string) => {
        if (query) {
          return this.YOURSERVICE.YOURMETHOD(query);
        }

        return of([]);
      })
    );
  }

  onSelect(event: TypeaheadMatch): void {
    this.selectedOption = event.item;
  }

your method should return an interface with a [name] property

This should be enough to get going. This is very old, but I passed through here before finding what I needed.

Baber answered 11/2, 2021 at 23:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.