Having some trouble with the ng2-completer plugin when trying to enable auto-complete functionality in a search box. The issue arises when attempting to use an array of objects instead of just strings, resulting in a 'No Results found' message. Even though the "name" field has been successfully loaded into the array, the search feature is not working as expected.
I am aiming to utilize ng2-completer for searching within an array of Person objects rather than simple strings.
The challenge here is that I need to search based on both name and address properties, which complicates the use of a simple string array.
I've experimented with various approaches, including Remote Data and Local data sources, but encountered failures specifically when dealing with classes. To test this out, I even implemented a basic version using the Angular Tour of Heroes tutorial and made some modifications according to my needs.
In the app.component.ts file:
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;
}
}
In the app.component.html file:
<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>
This implementation didn't produce the desired results, as shown by the following screenshot: https://i.sstatic.net/yr9TS.png