0

I have an issue with PrimeNg autocomplete : When i type any research, I obtain [Object Object] in the input text.

First I have an API call for getting a data set :

ngOnInit(): void {
  this.getCategories();
}

private getCategories(): void {
  const response = this.apiService.getCategories().subscribe(
    (data) => {
      this.categories = data as CategoriesModel[];
    }
  );
  console.log('Get categories');
  console.log('response ', response);
}

It allows me to retrive my data correctly (here is a sample) :

[
  {
    "id": "1",
    "categoryName": "Name1",
    "docDescription": "Description1 ..."
  },
  {
    "id": "2",
    "categoryName": "Name2",
    "docDescription": "Description2"
  }..
]

Now I try to handle my array of javascript objects in order to filter them :

I defined member variables in my component :

categories: CategoriesModel[];
filteredCategories: CategoriesModel[];
category: CategoriesModel;

I add this code into the HTML template:

<p-autoComplete
  [(ngModel)]="category"
  [suggestions]="filteredCategories"
  (completeMethod)="filterCategories($event)"
  [size]="30"
  [minLength]="1" placeholder="Hint: type a letter"
  [dropdown]="true">

  <ng-template let-category pTemplate="item.categoryName">
    <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">
      {{category.id}}
      <div style="font-size:18px;float:right;margin:10px 10px 0 0">{{category.categoryName}}</div>
    </div>
  </ng-template>

</p-autoComplete>
<span style="margin-left:50px">Category: {{category?.categoryName||'none'}}</span>

Now I try to use a filter method that will show in list results :

filterCategories(event): void {
  this.filteredCategories = [];
  // tslint:disable-next-line:prefer-for-of
  for (let i = 0; i < this.categories.length; i++) {
    this.category = this.categories[i];
    if (this.category.categoryName.toLowerCase().indexOf(event.query.toLowerCase()) === 0) {
      console.log(this.category.categoryName);
      this.filteredCategories.push(this.category);
    }
  }
}

1 Answer 1

1

I finally solved this by modifying the template :

<p-autoComplete
  [(ngModel)]="category"
  [suggestions]="filteredCategories"
  field = "categoryName"
  (completeMethod)="filterCategories($event)"
  [size]="30"
  [minLength]="1" placeholder="Hint: type a letter"
  [dropdown]="true">

  <ng-template let-category pTemplate="categoryName">
    <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">
      {{category.id}} {{category.categoryName}}
    </div>
  </ng-template>

</p-autoComplete>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.