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

What are the different ways in which :style is utilized in re-frame - with brackets, curly brackets, or simply without any characters?

For my current project, I am utilizing Clojure, ClojureScript, lein, shadow-cljs, Emacs, and CIDER to develop a dynamic web application. Typically, when building the project, I initiate the command cider-jack-in-cljs in Emacs, select shadow-cljs, opt for ...

Storing data in a text or HTML file using server-side JavaScript

Currently, I am working on a JavaScript form that involves saving user-entered variables to either a .txt file or a new webpage with the variables pre-filled in the inputs. I know that JavaScript cannot directly manipulate the user's machine, but I am ...

ng-bootstrap Datepicker with current date displayed as a placeholder

I have been using ng-bootstrap Datepicker and have implemented it like demonstrated in this example on Plunker. <div class="input-group"> <input class="form-control" placeholder="yyyy-mm-dd" name="dp" [(ngModel)]="model" ngbDatepicker ...

Explore the possibilities with Intel XDK's customizable keyboard feature

I recently started using Intel XDK for development and I encountered the following issue: I have an input text field (HTML) and I need to restrict user input to only numbers, decimals, and negative sign when they click on the field. How can I achieve this ...

Setting the height of CKEditor 5: A comprehensive guide

How can I adjust the height of the CKeditor angular component? The documentation suggests we can set the editor style to: min-height: 500px !important; However, this solution does not seem to be effective for me. Any other suggestions? ...

Passing component properties using spaces in VueJS is a simple and effective

I am encountering an issue where I want to pass component props from my view, but I am facing a challenge due to the presence of a space in the value. This causes Vue to return the following error: vendor.js:695 [Vue warn]: Error compiling template: - inva ...

Why isn't my SCO considered complete?

My SCO is very basic, with an empty html page. I am utilizing the pipwerks scorm api wrapper in Chrome dev tools to establish a connection to the LMS, set cmi.completion_status to "completed", and cmi.success_status to "failed" (as outlined in the scorm ru ...

Artboard: Easily navigate through pictures

As part of a school assignment, I wanted to create an interactive story where users can click through images using the UP and DOWN buttons. However, I am facing an issue with my If function overriding the previous function. I envision this project to be a ...

Navigating to the Login page in Angular 13

<app-navbar></app-navbar> <div class = "app-body"> <div class="app-sidebar"> <app-sidebar></app-sidebar> </div> <div class="app-feed"> <router-outlet name="main& ...

The datetimepicker is not functioning properly

I'm experiencing an issue with the datetimepicker where it doesn't display a calendar when I click the icon. Interestingly, the Chrome browser isn't showing any errors in the development console. <script src="Scripts/jquery-2.1.1.min.js ...

PUPPETER - Unpredictable pause in loop not functioning as expected

Having an issue with this specific part of the code: (async () => { const browser = await puppeteer.launch({ headless: false, // slowMo: 250 // slow down by 250ms }); const page = await browser.newPage(); //some code // CODE ABOVE WORKS, ...

Vue.js - Error: Module not found: Cannot locate module 'lottie-vuejs'

I've been attempting to integrate lottie-vuejs into my project. After running the npm install command and following the steps outlined here, I encountered an issue. Unfortunately, I received the following error message: Module not found: Error: Can ...

The issue of batch-wise data clustering on Google Maps when zooming in or out

//The code snippet provided below initializes a map with specified settings and clusters markers based on the data sent in patches of 10000.// var mapDiv = document.getElementById('newmap'); map = new google.maps.Map(mapDiv, { center ...

Validating checkboxes using HTML5

When it comes to HTML5 form validation, there are some limitations. For instance, if you have multiple groups of checkboxes and at least one checkbox in each group needs to be checked, the built-in validation may fall short. This is where I encountered an ...

The error message "The function 'combineLatest' is not found on the Observable type"

Hey there! I'm currently working on implementing an InstantSearch function into my website using Angular 12.2. To accomplish this, I'll be working with a Firestore database with the index "book-data". In my search component, I have included the f ...

Unit testing in Angular ensures that a property is always defined and never undefined

I'm struggling to understand why this basic test isn't functioning properly. BannerComponent is not supposed to display a welcome message upon construction Expected 'welcome' to be undefined. // Component @Component({ selector: &ap ...

navigating to the start of a hyperlink

I'm having issues with scrolling to anchors and encountering 3 specific problems: If I hover over two panels and click a link to one of them, nothing happens. When I'm on section D and click on section C, it scrolls to the end of section C. ...

Exploring the capabilities of Dynamic Route integration with Server Side components using Supabase in Next.js

export default async function Page({ searchParams, }: { searchParams?: { [key: string]: string | string[] | undefined }; }) { // const searchParams = useSearchParams(); const id = searchParams?.p ?? "aaa"; // default value is "1" ...

Submitting multiple forms using AJAX and PHP

I am currently trying to send the form data to another page for processing, but I am not receiving any data. Below are the forms in question: The default form is the login form for requesting a username and password, with only one submit button. ...

Tips for preventing the browser from freezing when incorporating a large HTML chunk retrieved through AJAX requests

I've developed a web application that showcases information about various items. Initially, only a small portion of the items are displayed at the top level. Upon loading the page for the first time and displaying these initial items, I make an AJAX r ...