ng2-completer does not return any search results while searching on an array of objects

偶尔善良 提交于 2020-03-10 05:14:10

问题


I am trying to use ng2-completer for auto-completing in a search box and it does not work except for an array of strings. I get 'No Results found'. From the screenshot it can be seen that "name" has been loaded into the array.

I want to use ng2-completer to search on an array of (say) Person.

But need to search on name and address and so I cannot just use a string[].

Tried a number of approaches: both with Remote Data and also with Local but both fail when using a class. I have tried a simple version on the classic Angular Tour of Heroes tutorial. Here are my changes.

app.component.ts

import { Component } from '@angular/core';
import { CompleterService, CompleterData } from 'ng2-completer';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Tour of Heroes';
  protected searchStr: string;
  protected dataService: CompleterData;
  searchData: Array<Person> = [];
  constructor(private completerService: CompleterService) {
    this.dataService = completerService.local(this.searchData, 'name', 'person');
    for(let i=0; i<10; i++) {
      let p = new Person(
        i, 
        "name" + i,
        "address" + i,
        1000);
      this.searchData.push(p);
      console.log("person["+i+"] :" + p.id + " " + p.name + " " + p.address);
    }
  }

}

export class Person {
  id: number;
  name: string;
  address: string;
  income: number;
  constructor(id:number, name:string, address:string, income:number) {
    this.id = id;
    this.name = name;
    this.address = address;
    this.income = income;
  }
}

app.component.html

<h1>{{title}}</h1>
<nav>
  <a routerLink="/dashboard">Dashboard</a>
  <a routerLink="/heroes">Heroes</a>
</nav>
<h1>Search person</h1>
            <ng2-completer [(ngModel)]="searchStr" [datasource]="dataService" [minSearchLength]="0"></ng2-completer>
            <h1>Search captain</h1>
<div style="width:100px;height:100px;border:1px solid rgb(255, 255, 0);">This is app component!</div>

<router-outlet></router-outlet>
<app-messages></app-messages>

failed


回答1:


Looks like you are using titleField in the wrong way. According to the documents it's the field which will be displayed as search result from your input data.

Try this

this.dataService = completerService.local(this.searchData, 'name', 'name');

or

this.dataService = completerService.local(this.searchData, 'name', 'address');

Stackblitz here



来源:https://stackoverflow.com/questions/60022338/ng2-completer-does-not-return-any-search-results-while-searching-on-an-array-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!