Angular PrimeNg 使用自动完成并传递 REST 对象

Angular PrimeNg Using autocomplete and passing REST object

我对 PrimeNg 自动完成有疑问: 当我输入任何研究时,我在输入文本中获得 [Object Object]。

首先,我有一个 API 请求获取数据集:

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);
}

它允许我正确地检索我的数据(这里是一个示例):

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

现在我尝试处理我的 javascript 对象数组以过滤它们:

我在我的组件中定义了成员变量:

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

我将此代码添加到 HTML 模板中:

<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>

现在我尝试使用将显示在列表结果中的过滤方法:

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);
    }
  }
}

我终于通过修改模板解决了这个问题:

<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>