0

auto-complete is not working , dropdown is loaded the first time and once i try to type something is not filtering then dropwdown values are gone service.ts

 getUserLocations(UserID: string, allList:string  ) {
        return this._http.get(environment.BASE_API_URL + 'xxxxx/' + ID + '/' + allList)
            .map((response: Response) => response.json())
              .do(data => console.log('locations ' + JSON.stringify(data)))
            .catch(this.handleError);
    }

compnent.ts

        brand: any [];
        filteredBrands: any[];
       GetUserLocations(PNSLUID: string, allList: string) {
                   this._searchService.getUserLocations(ID, allList)
                .subscribe(
                data => {
                    this.brand= data.result.name;//not sure how to bind the id
                },
                error => console.log('GetControls Method: ' + <any>error, 'alert alert-danger'));
        }

   filterBrands(event) {
        this.filteredBrands = [];
        for (let i = 0; i < this.brand.length; i++) {
            let brand = this.brand[i];
            if (brand.toLowerCase().indexOf(event.query.toLowerCase()) == 0) {
                this.filteredBrands.push(brand);
            }
        }
    }

html

<p-autoComplete  [(ngModel)]="brand" [suggestions]="filteredBrands" (completeMethod)="filterBrands($event)" [size]="30"
                                                [minLength]="1" placeholder="Office" [dropdown]="true">
                                    <ng-template let-brand pTemplate="item">
                                        <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">

                                            <div style="font-size:18px;float:right;margin:10px 10px 0 0">{{brand}}</div>
                                        </div>
                                    </ng-template>
                                </p-autoComplete>

The issue is it is not populating the auto-complete dropdown..there s an issue with binding

*************************************************UPDATE***************************************************** issue: example: my dropdown has the following values

  1. region a

  2. region b

  3. region c

  4. HBV office

  5. Di office

if I type region auto-complete does not work it still display all values, however, if I select region b then start removing b then auto complete works..in other words..it works only if I select a value but if I start from empty text and start typing it does not work

html

 <p-autoComplete name="OfficeList" [(ngModel)]="val" [suggestions]="results" (completeMethod)="search($event)"  field="name" dataKey="id" [dropdown]="true"></p-autoComplete>

interface

export interface IOffices {
    id: number,
    name:string
}

component

    val: IOffices;
    results: IOffices[];  
    originalResults: IOffices[];

 GetUserLocations(PNSLUID: string, allList: string) {
              this._searchService.getUserLocations(PNSLUID, allList)
            .subscribe(
              data => {
                  this.results = data.result;
                 this.originalResults = data.result; 
          },
          error => console.log('GetControls Method: ' + <any>error, 'alert alert-danger'));
            })
    }

search(event) {
            console.log("result 2 : " + this.originalResults.length.toString());
    console.log("event : " + event.query.toString());

    this.results = this.originalResults;

    this.results = this.results.filter(data => 
       data.name.indexOf(event.query) !== -1);

    }
rgoal
  • 1,236
  • 11
  • 35
  • 61
  • Where are you setting you brand options that should be in *filteredBrands* variable? – JuanDM Apr 11 '18 at 00:06
  • updated my above code... The issue is it is not populating the dropdown..there s an issue with binding – rgoal Apr 11 '18 at 15:44
  • I suspect it is a Typo... `for (let i = 0; i < this.brand.length; i++)` in this line you are trying to iterate `brand` varible instead of `brands` with **S** that actually store the values returned by the API – JuanDM Apr 11 '18 at 18:10
  • I have already fixed that but i am still getting an error upon binding the data to the auto-complete dropdown error 'If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions." – rgoal Apr 11 '18 at 18:47
  • I dont know if you already tried this, but from the angular docs _" Defining a name attribute is a requirement when using [(ngModel)] in combination with a form."_ https://angular.io/guide/forms, just weird because the autocomplete docs doesn't even mention that property but give it a try. – JuanDM Apr 11 '18 at 18:59
  • thanks for sharing the link, i am still error "Cannot read property " location undefined" I think the issue is I am unable to figure out how to bind "location" and "id" o the auto-complete dropdown correctly. I confirmed I get the json back from the service correctly – rgoal Apr 11 '18 at 20:12
  • I cant see in you code where are you binding location? can you update your question sharing your actual code? and also an example of the value of `data.result` – JuanDM Apr 11 '18 at 21:22
  • sorry I meant to say "Name" this is the issue i think "this.brand= data.result.name;" method GetUserLocations – rgoal Apr 11 '18 at 21:49

1 Answers1

4

Seems that you are using the code posted in the primeng site.. Take a look to the section Objects in their docs

This code works with strings and if i understood your code you are trying to bind an object.

So my suggestion is:

  • If you are binding objects you should use the attribute field in the autocomplete to set the object property you wanna show to the user.

  • The variable that you put in your NgModel(you can use an entire object) should has "the same type" that the objects in the array of suggestions.

  • For dropdown functionallity on click use the onDropdownClick event

HTML

<p-autoComplete name="OfficeList" [(ngModel)]="brand" [suggestions]="filteredBrands" (completeMethod)="filterBrands($event)" 
                 [size]="30" [minLength]="1" placeholder="Office" [dropdown]="true" (onDropdownClick)="GetUserLocations()">
 </p-autoComplete>

Component.ts

brand: any [];
filteredBrands: any[];

GetUserLocations(PNSLUID: string, allList: string) {
    this._searchService.getUserLocations(ID, allList)
        .subscribe(
            data => {
                this.results = data.result; // You should put the entire array of objects here
            },
            error => console.log('error'));
    }

search(event) {
        this.results = this.results
                           .filter(data => data..toString()
                           .toLowerCase()
                           .indexOf(event.query.toString().toLowerCase()) !== -1);
}

Doing this adjustments it should work.

A working example: https://primeng-autocomplete-example.stackblitz.io/

hope it helps.

JuanDM
  • 1,250
  • 10
  • 24
  • Thanks for your input.still does not work ..i have updated my code above..I am closer to the solution now – rgoal Apr 12 '18 at 17:16
  • updated my answer...from this.results = this.results.find(data => data.name.indexOf(event.query) !== -1);'''(this.results) throws an error – rgoal Apr 12 '18 at 18:45
  • the error from this.result"Severity Code Description Project File Line Suppression State Error TS2322 Type 'IOffices' is not assignable to type 'IOffices[]'. Property 'find' is missing in type 'IOffices'. – rgoal Apr 12 '18 at 18:46
  • my mistake instead of `find` use `filter` – JuanDM Apr 12 '18 at 18:53
  • now it s binding the values to the dropdown which is a step forward, but auto complete is not ..an error is thrown on the browser " If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions" – rgoal Apr 12 '18 at 19:04
  • try setting the `name` attribute to the autocomplete tag – JuanDM Apr 12 '18 at 19:07
  • no errors now but auto-complete is not working , dropdown is loaded the first time and once i try to type something is not filtering then dropwdown values are gone..updated my above code – rgoal Apr 12 '18 at 19:24
  • Im assuming that the `results` variable has information before filtering.. can you debbug the search method and see if the `results` variable has data when you try to filter it? – JuanDM Apr 12 '18 at 19:27
  • did some work ..updated my code..basically I removed (onDropdownClick)="GetUserLocations()" from my html as I am loading the dropdown from noOnInt event. I did debug result and it was empty so I copied the original values to another array and everytime I do search I just reload the values back to this.results...this way values are always there when i expand my dropdown. the only issue is my auto - complete is not working properly ...see above code – rgoal Apr 12 '18 at 21:09
  • I decided to create an example in stackblitz (https://primeng-autocomplete-example.stackblitz.io/) also added to the answer – JuanDM Apr 12 '18 at 22:57