Searching through an array of objects with ng2-completer does not yield any search results

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

Answer №1

It appears that the titleField is being utilized incorrectly in your code. The documentation specifies that this field should be the one displayed as the search result from the input data.

Consider trying either of the following:

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

or

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

Check out the Stackblitz example here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Error encountered: Module not found - Issue resolving module" while using signrequest-client in Angular

I've been attempting to integrate the signRequest API into my angular application. To do so, I first installed the signrequest-client using the following command: npm install signrequest-client --save Following this installation, I included the Ja ...

extract keys and values from an array of objects

I would like assistance with removing any objects where the inspectionScheduleQuestionId is null using JS. How can we achieve this? Thank you. #data const data = [ { "id": 0, "inspectionScheduleQuestionId": 1, ...

Exploring Angular: Enhancing Routing through GET Requests

I've been working on a cutting-edge application that combines an Angular 2 frontend with a powerful Java backend. An exciting feature of this application is a dynamic form, consisting of various search criteria. Upon submission, I execute an http get ...

Guide to making a TreeView in Angular 2 with Typescript

How can I implement a TreeView in Angular 2 using Typescript? I have searched on Google but have not found any working examples, etc. Could someone kindly provide me with an example to help me accomplish this task? ...

Unable to establish a simulated environment and trial period for experimentation

I encountered the following errors during the test: TypeError: Cannot read properties of undefined (reading 'subscribe') Error: <toHaveBeenCalled> : Expected a spy, but got Function. I am having trouble understanding these errors. Here i ...

I'm encountering an error while trying to build my Ag-Grid using npm run build, can someone help me figure out

Being relatively new to Next.js and web development in general, my background mainly consists of working with compiled languages. I recently embarked on a project to build a web app using Ag-Grid, drawing inspiration from an example I found on a public Git ...

What is the reason behind Angular FormControl applying the 'disabled' attribute in the DOM but not the 'required' attribute?

After transitioning my form logic from the template to FormGroup & FormControl objects, I noticed that when a FormControl is disabled in Angular, the 'disabled' attribute for the field is automatically updated in the DOM. However, when I modi ...

The error "Cannot access property afs (Angularfirestore) of undefined in the collection.set()" occurred

In the current code snippet below, I am iterating over a collection of data and updating a field if the email matches. The issue arises when trying to set new values where it crashes. The iteration process itself functions correctly, with afs being Angular ...

Transferring information between two components in separate Angular 4 modules

Within my application, I have defined two modules named AppModule and UserModule. I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule). Below is a snippet of app.componen ...

How to deliver various static files in NestJS using different paths and prefixes?

I've set up static file serving for developer documentation using the following code: app.useStaticAssets(docsLocation, { prefix: "/docs/" }) Now I have another directory with more static content that I want to serve. Is it possible to serve from ...

The functionality of Flowbite Drawer is disabled when used within an ngFor loop in Angular

Currently, I am utilizing Flowbite () as a Tailwind CSS plugin in my Angular project. Everything is functioning perfectly except for an issue that arises when I try to call a drawer button within a table generated using ngFor. Unfortunately, I am at a los ...

Nested interfaces can utilize sum types

An example showcasing the use of sum types: interface Cash { amount: number, type: 'cash' } interface Card { amount: number, type: 'card', cardNumber: string } type Payment = Cash | Card const displayPayment = (payment: Pay ...

Problem with Angular 2 Typings Paths in Typescript

Currently, I am in the process of learning how to create a Gulp build process with Angular 2 and Typescript. Following the Quick Start guide has allowed me to get everything up and running smoothly. However, I have decided to experiment with different fold ...

In fact, retrieve the file from an S3 bucket and save it to your local

I've been attempting to retrieve an s3 file from my bucket using this function: async Export() { const myKey = '...key...' const mySecret = '...secret...' AWS.config.update( { accessKeyId: myKey, secretAcces ...

Using ngModel instead of value to bind a custom Angular directive for currency input

Currently, I am using a specialized mat-input-currency format directive to automatically convert my field inputs into currency. You can find the npm repository here. However, the directive binds the element data to [value] of the input, and I require it t ...

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: https://i.sstatic.net/zzm8f.png My intention was to have the menu displayed below the content page while keeping the menu button visible. Howe ...

Top Method for Connecting Numerous Dependent HTTP Requests Without the Need for Multiple Subscriptions and Iterations

I'm working on an angular project where I have an API that creates a line item and then loops through to call the API for each modification before firing the print request. Currently, I am using multiple subscribes for this process and I was wondering ...

The browser is unable to load the Angular app's component

I'm having trouble with my index.html and main.ts files. The browser just displays "loading..." and doesn't load the component I created. Can someone please assist me? <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap. ...

What potential issue could result in a property length of null error while working with a Material Data Table?

I'm experiencing a similar issue as the one discussed in this post, but none of the suggestions there have resolved my problem, and my scenario has some differences. In my case, a parent component is assigning an array to a child component's inp ...

Using the className prop in React with TypeScript

How can the className prop be properly typed and utilized in a custom component? In the past, it was possible to do the following: class MyComponent extends React.Component<MyProps, {}> { ... } and then include the component using: <MyCompone ...