"Enhance Your Search with PrimeNG's AutoComplete

Currently, I am attempting to implement the autocomplete feature from primeNg based on their documentation, but I am facing issues with displaying the suggestions.

  1. Firstly, I added the AutoComplete module by importing it:
    import { AutoCompleteModule } from 'primeng/autocomplete';
  2. Then, I included the module in my imports array:
    imports: [CommonModule, FormsModule, AutoCompleteModule],
  3. Below is a snippet of the code I have implemented:
Here is a part of my .html file:

<div fxLayout="column">
    <div>
        <h1>Hero Search</h1>
        <p-divider></p-divider>
    </div>
    <div>
        <p-autoComplete  [(ngModel)]="selectedHero" [suggestions]="cambiar()" (completeMethod)="filterHeros($event)" field="name" [minLength]="1"></p-autoComplete>     
    </div>

</div>

Here is part of my component file:

import { Component, OnInit } from '@angular/core';
import { Heroe } from '../../interface/heroes.interface';
import { HeroesService } from '../../services/heroes.service';

// Additional component details...

My service file:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { Heroe } from '../interface/heroes.interface';

// Further service details...

The primeNg documentation states that for suggestions:

name:suggestions Type:array Default:null Description:An array of suggestions to display.

Despite trying to pass the array as both string[] and any[], I have been unsuccessful in getting the suggestions to appear. Any assistance you can provide would be greatly appreciated. Thank you.

Answer №1

Problem 1

Since you are filtering by the superhero property,

Incorrect:

<p-autoComplete  
    ...
    field="name">
</p-autoComplete>

Solution for Problem 1

Update as follows:

<p-autoComplete  
    ...
    field="superhero">
</p-autoComplete>

Problem 2

In this function, you are returning a string array. However, in HTML, you are using the attribute field="name", which is meant for object arrays (Refer to PrimeNG | AutoComplete (Object section)).

cambiar(){
  let mostrar:any[] = [];
  for (let i = 0; i < this.filteredHeros.length; i++){
    mostrar[i] = this.filteredHeros[i].superhero
  }
  return mostrar;
}

Solution 1 for Problem 2

Return the filteredHeros array instead.

cambiar() {
  return this.filteredHeros;
}

OR

Solution 2 for Problem 2

Pass the filteredHeros array to [suggestions].

<p-autoComplete
    ...
    [suggestions]="filteredHeros">
</p-autoComplete>

Check out a Sample Demo on StackBlitz

Answer №2

Utilize the cambiar method within the filterHeros function, such as the following example:

filterHeros(event:any){
    let filtered : Heroe[]= [];
    let query = event.query;
    for (let i = 0; i < this.heroes.length; i++) {
      let heroe = this.heroes[i];
      if (heroe.superhero.toLowerCase().indexOf(query.toLowerCase()) == 0) {
        filtered.push(heroe);
      }
    }
    this.filteredHeros = filtered;
    this.cambiar();
  }

Since it is only updated upon loading, we have also updated it on the (completeMethod) event to retrieve the filtered array

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

Angular 2: Enhancing Tables

I am looking to create a custom table using Angular 2. Here is the desired layout of the table: https://i.sstatic.net/6Mrtf.png I have a Component that provides me with data export class ResultsComponent implements OnInit { public items: any; ngO ...

Issue with NGRX: component does not reflect state changes

Whenever I click on a button, it is supposed to open up a Google map. Upon clicking, I can see Google scripts being inserted, which triggers a callback that sends a message to my reducer. After receiving the message, I can confirm through logging that the ...

Utilize API within an array to enable Ionic to display a PDF in a document viewer

Recently diving into the world of Angular and Ionic, I've come across some interesting API data: [{"ID":"1","Title":"Maritime Safety","File_Name":"9c714531945ee24345f60e2105776e23.pdf","Created":"2018-11-07 17:36:55","Modified":"2018-11-07 17:36:55"} ...

Error: When running the NPM CI command in a GitHub action, the package nice-napi is not accessible from

I've recently set up a Github action to build and run tests on every pull request. However, the action suddenly stopped working even though no changes were made to the code base. Here is the current code for the action: name: Test pull request on: ...

The Angular 6 test command using npm has encountered a failure

I've been encountering a disconnect error while attempting to run Angular test cases. With over 1500 test cases written, it appears that the sheer volume may be causing this issue. Is there a way to resolve the disconnect error when running such a lar ...

Tips for validating Enum Strings using the newest version of Joi?

Is there a way to validate Enum String? In the past, I followed this advice from: https://github.com/hapijs/joi/issues/1449 enum UserRole { Admin = 'admin', Staff = 'staff' } const validator = { create: Joi.object().keys({ ...

Issue with connecting React Router v4 to Redux - dispatch function not being properly passed

Recently, I've been working on migrating my app to React Router v4 and encountered some challenges due to the significant changes in the API. Here's where I currently stand: Setting Up the Router const createStoreWithMiddleware = applyMiddlewar ...

Changing JSON names to display on a webpage

I am looking to modify the name displayed in a json file for presentation on a page using ion-select. mycodehtml ion-select [(ngModel)]="refine" (ionChange)="optionsFn(item, i);" > <ion-option [value]="item" *ngFor="let item of totalfilter ...

How to Use a For Each Loop with Google Maps DrawingManager to Create Polygons?

My Ionic 4 Application using Angular 8 incorporates a google maps component where I need to draw and edit multiple polygons, eventually saving their vertices in a database. Hard coding some polygons is easy with getPath() or getPaths(), but I'm utiliz ...

Tips on setting the first root element to automatically expand in a tree component

Currently, I am utilizing a tree component that includes partially loaded data. For reference, here is the link to the stackblitz example: StackBlitz. Is there a way for me to have the child element of the first root element automatically opened by defau ...

Converting Data Types in Typescript

So I'm working with Data retrieved from a C# Rest Server. One of the values in the array is of type Date. When I try to perform calculations on it, like this: let difference = date1.getTime() - date2.getTime(); I encounter the following error messag ...

Is there ever a need for additional directives in Angular reactive forms besides [formControl]?

Since the inception of Angular 2, I have been utilizing Angular reactive forms extensively. I always incorporate directives like formGroup, formGroupName, formControl, formControlName, and formArrayName in my projects. However, recently I pondered if usin ...

Angular app experiences a breakdown due to a JitCompiler issue

After being given the responsibility of enhancing a project, I diligently added new modules and components. However, upon running the application, it crashes. Uncaught Error: Component EnquiryComponent is not part of any NgModule or the module has not bee ...

Tips for changing a created Word file with Docxtemplater into a PDF format

Hey there! I am currently in the process of building a website with Angular.js and have successfully managed to generate a word document from user input. Everything was working fine until I encountered an issue. I now need to provide a way for users to pr ...

Active Angular component utilizing *ngIf during the programmatically lazy loading of a Module

I find myself in a situation where I need to load numerous components on a specific route within my application. These components are controlled by a logic with *ngIf directives that allow me to show or hide them dynamically. For instance: <div *ngIf=& ...

You cannot invoke this expression while destructuring an array of React hooks in TypeScript

Within my React TypeScript component, I have several fields that check a specific condition. If the condition is not met, the corresponding field error is set to true in order to be reflected in the component's DOM and prevent submission. However, whe ...

Maintain division contents while navigating

I need a solution to keep my div (NewCall) open even when the user navigates between pages in my Single Page Application. The NewCall div is located in my layout page and is triggered by user click. However, whenever I navigate to another page, the div cl ...

Does the reactive form trigger a custom validator function upon creation?

Why does the formInit function call isPassValid when constructing the form to check for a valid password? ngOnInit() { this.formInit(); } formInit() { this.form = this.fb.group({ password: ['', [Validators.required, this.i ...

Unable to inject basic service into component

Despite all my efforts, I am struggling to inject a simple service into an Angular2 component. Everything is transpiling correctly, but I keep encountering this error: EXCEPTION: TypeError: Cannot read property 'getSurveyItem' of undefined Even ...

angular typescript does not support receiving a value in foreach loop

It seems that I'm facing an issue with retrieving the element value inside a typescript foreach loop. constructor(db: AngularFireDatabase) { } this.fbUserData = this.db.list('users/'+this.userid).valueChanges() this.fbUserData.forEa ...