Autocomplete feature in Angular not showing search results

I am currently using ng-prime's <p-autocomplete> to display values by searching in the back-end.

Below is the HTML code I have implemented:

<p-autoComplete [(ngModel)]="agent" [suggestions]="filteredAgents" name="agents" (completeMethod)="filterAgents($event)"  [size]="10"
                    placeholder="Agents" [minLength]="3"></p-autoComplete>

Within the component.ts file, I initialize the array at the start of the component like this:

filteredAgents: string[] = [];

I also have a method that sends queries to the back end and then adds them to the array:

 filterAgents(event) {
    let query = event.query;
    this._agentsService.getAgentSearch(query).subscribe(result => {
      result.items.forEach((value) => {
            this.filteredAgents.push(value.name);
            console.log(this.filteredAgents);
       });
    });
}

While I can see the filtered values in the console, they are not showing up in the suggestions. What could be causing this issue?

Answer №1

AutoComplete utilizes either setter based checking or ngDoCheck to determine if the suggestions have changed in order to update the UI. The immutable property is used to configure this behavior; when enabled (default), setter based detection is used. This means that any changes such as adding or removing a record should always result in creating a new array reference instead of manipulating an existing one because Angular does not trigger setters if the reference remains unchanged. (Extract from Angular documentation)

Using Array.prototype.push does not create a new reference, but rather mutates the original array. Therefore, it is essential to create a new array.

 filterAgents(event) {
    let query = event.query;
    this._agentsService.getAgentSearch(query).subscribe(result => {
            this.filteredAgents = [...result.items.map(e => e.name)]
        });
    }

I extracted the names from the result using map method.

Answer №2

If you have an array of objects representing filtered agents, consider including the attribute "field=name" in the directive.

In this case, "name" refers to a specific field within each object that the directive will use to populate suggestions.

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

When testing on jsfiddle, the script functions properly with pure JavaScript. However, when integrating it into my own code, it fails to work unless jQuery is included

Visit this link to access the code snippet. Below is my code: const chk = document.getElementById('chk'); const body = document.body; $(function(){ chk.addEventListener('change', () => { $('.body').toggleClass( ...

I am unable to determine if I have already selected a List Item

My goal is to have a functionality where clicking on "Download Drivers" will open the list, and clicking again will close it. This should be achieved with onclick events only, no hover effects. Additionally, I want the list to remain open even if I click o ...

The application's user interface is currently unable to access the REST API of the SSO Server

In the Angular front end, we are encountering an issue where it cannot call the REST API of the SSO server in the customer's environment to retrieve the open-id configuration. There doesn't seem to be any network calls being made when checked in ...

Material Ui and react-router onClick event latency on handheld devices

My React application is currently using @material-ui/core v.1.2.1 and react-router 3.0.2, which I am unable to update at the moment. Whenever I click a button that handles navigation, there is a noticeable delay of around 2 seconds before it works. In ord ...

Creating a dynamic word cloud in D3: Learn how to automatically adjust font sizes to prevent overflow and scale words to fit any screen size

I am currently utilizing Jason Davies' d3-cloud.js to create my word cloud, you can view it here 1. I'm encountering an issue where the words run out of space when the initial window size is too small. To address this, I have a function that cal ...

How can you tap into local storage in CSS while utilizing a chrome extension?

Can I access local storage from a Chrome extension's options file using CSS? Is it possible to use JavaScript to define a variable that can be utilized in CSS, or is local storage only accessible through JavaScript? If local storage is restricted to J ...

Notifying asynchronous completion using Gulp, Babel, and configuration file config.yml

My current project involves using babel and gulp for handling tasks, as well as loading a yml config file for paths. This is the content of cofing.yml: PATHS: # Path to source folder sources: "jet/static/jet_src" # Path to dist folder dist: "jet/ ...

Tips for navigating through complex JSON structures with JavaScript or JQuery

I'm currently navigating the complexities of parsing a multi-level JSON array as a newcomer to JSON. I am seeking solutions using either JavaScript or jQuery. My goal is to extract the application id, application description, and Product description f ...

How can a producer know when it's time to send a message in NodeJS using ZeroMQ?

After conducting some research on patterns supported by zeromq, I have encountered an issue with the PUB/SUB pattern in my recent project as well as the PUSH/PULL pattern. I am using NodeJS for the zeromq implementation. In my examples (server.js & client ...

Tips for transmitting a batch of resources with Restangular?

Suppose I need to make a DELETE request to delete multiple products from the resource /products. The complete request should be sent to this URI: /products/ids=1&ids=2&ids=3 What is the method to send a request like this using Restangular? The c ...

Steps for updating a server component after redirectionWould you like to know how

One of my server components fetches and displays data only when the user is authorized: function CheckAuthorization() { const isAuthenticated = // check if user is authorized return ( <div> {isAuthenticated ? ( <DisplayAutho ...

Inaccurate data is being shown by the Ajax method

I have a question that I haven't been able to find a satisfactory answer for: Recently, I started learning about AJAX methods and I'm trying to post some information processed by a php page named page.php. In my HTML file, I've included th ...

What is the best method for displaying an HTML string within an HTML file in Angular 5?

I have declared an array in my TypeScript file like this: import {Component, OnInit} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-foo', template: ...

What is the best way to cancel an interval set by a function within a functional component?

When using useEffect, it's easy to clear an interval like this: useEffect(() => { const interval = setInterval(some function, time); return () => clearInterval(interval) }) But what if I need to set an interval inside a function? Do I hav ...

Creating an Array of dynamically generated elements using jQuery

A dynamic table is being generated using jQuery's .append() function: $el.append('<tr data-id=' + data[i].id + ' data-token=' + data[i].token + '><td>' + data[i].order + '</td>\n\<td&g ...

Unable to invoke the jQuery datetimepicker function within a personalized directive

I have created a unique time picker directive in AngularJS to display a datetimepicker. app.directive("timePicker", function() { return { restrict: "A", link: function(scope, elem, attrs) { / ...

Unable to utilize the useState hook in TypeScript (Error: 'useState' is not recognized)

Can you identify the issue with the following code? I am receiving a warning from TypeScript when using useState import * as React, { useState } from 'react' const useForm = (callback: any | undefined) => { const [inputs, setInputs] = useS ...

Expression fragment in Thymeleaf

In splitting my templates into head/main/footer parts using thymeleaf, I have found a method to include stylesheets and javascript on certain pages while excluding them from others. This is achieved through the use of fragment expressions outlined here. M ...

What strategies can I use to prevent making multiple API calls inside setInterval when initializing a new connection in a socket?

I am currently working on implementing a socket system where users can request a function with an ID, and after receiving the ID, I send requests to an API every second and emit the response back to the user. Issue: Every time a new user requests the same ...

having trouble with npm installation of firebase-tools

I am encountering an issue while attempting to set up firebase-tools for my android studio project. Here is the error message that I am facing: Microsoft Windows [Version 10.0.15063] (c) 2017 Microsoft Corporation. All rights reserved. C:\WINDOWS&bs ...