How can you control the search results limit in Angular 2 using ng2-completer?

Utilizing ng2-completer within my application has been a seamless experience so far. When users start entering text, it triggers an API call to fetch records from the server. However, I have encountered an issue where if the completer returns more than 50 entries, it ends up overlapping the entire screen. How can I limit the dropdown length to prevent this overlap?

Although I attempted to resolve this with the following CSS code, it did not yield the desired outcome.

.completer-dropdown {
   overflow-y: auto !important;
   max-height: 100px !important;
 }

Below is a snippet of my HTML code:

<ng2-completer  placeholder="Enter Your Locality Name" class="overlay" [dataService]="dataServiceForLocality" [minSearchLength]="3" [fieldTabindex]="2" [(ngModel)]="localityValue" (selected)="selectedLocality($event)" [textSearching]="'Please wait...'" formControlName="locality" style="height: 50px;" (keyup)="onKey($event.target.value)"></ng2-completer>


You can view a live example of this implementation here.

https://i.sstatic.net/O2ydM.png

Answer №1

It appears that the current version of ng2-completer does not have support for this particular feature at the moment.

Regardless, even if ng2-completer were to include the feature, it is more efficient for your data service to handle the maximum number of items. It is recommended to only return the first 10-20 items that are found, rather than returning the entire dataset to the client. Imagine if thousands or more items were returned?

If a user is presented with too many items, they will likely understand the need to refine their search criteria.

Edit: After reviewing the CSS classes, it seems that you were close in implementing the necessary changes. In my case, adjusting the styles directly on the demo page worked well. This involved modifying the page's CSS like so:

.completer-dropdown[_ngcontent-tsn-1] {
    max-height: 200px !important;
    overflow-y: scroll;
    overflow-x: hidden;
    ...
}

Refer to the image below for further clarification:

https://i.sstatic.net/iNRsA.png

Answer №2

Currently, ng2-completer does not support this feature.

To limit the number of records retrieved, it is recommended to only request 10 to 12 records from the API.

Answer №3

It is possible, but it is important to note that angular 2 utilizes view encapsulation. Since ng2-completer is a separate component, styling it without using the /deep/ or >>> selectors will not have any effect.

To limit the dropdown length, you can define the following styles within the containing component:

:host >>> .completer-dropdown {
    overflow-y: auto;
    max-height: 200px;
}

Alternatively, you can filter the items before passing them to ng2-completer by creating a custom CompleterData and altering its output:

import { Http, Response } from "@angular/http";
import { Subject } from "rxjs/Subject";

import { CompleterData, CompleterItem } from "../src";

export class CustomData extends Subject<CompleterItem[]> implements CompleterData {
    constructor(private http: Http) {
        super();
    }
    public search(term: string): void {
        this.http.get("http://example.com?seacrh=" + term)
            .map((res: Response) => {
                let data = res.json();
                
                // Manipulate the result as needed
                data = data.slice(0, 10);

                // Convert the result to CompleterItem[]
                let matches: CompleterItem[] = data.map((item: any) => this.convertToItem(item));
                // pass the result to ng2-completer
                this.next(matches);
            })
            .subscribe();
    }

    public cancel() {
        // Handle cancel if necessary
    }

    public convertToItem(data: any): CompleterItem {
        if (!data) {
            return null;
        }
        
        return {
            title: typeof data === "string"? data : data.text
        }
    }
}

Check out the plunk demo.

Answer №4

Absolutely, I believe this solution has proven to be effective

ng2-auto-complete{
    height: 250px; 
    overflow-y: auto; 
    overflow-x: hidden;
}

Answer №5

To ensure smooth scrolling when navigating with the up and down arrows in ng2-complete, make sure to apply overflow-y: auto;. This will automatically adjust the scroll position as you select different times.

Answer №6

Although this question may be old, there could still be someone facing the same issue and in need of assistance. I approached solving this problem in a unique way due to the large amount of data in my project. With a search list containing up to 10,000 strings, simply hiding objects was not a viable solution for me as it would overwhelm older computers or smartphones used by potential users. While using cdk-virtual-scrolling was an option, modifying a full component didn't sit well with me.

My solution involved modifying the array before passing it to ng2-completer, inspired by Ofer Herman's earlier explanation. However, in my case, I was dealing with an offline array.

I began by adding [(ngModel)]="searchText" to the ng2-completer tag. In my component's TypeScript file, I implemented the following logic:

preSearchFilter() {
   this.filteredArray = this.searchOptions.filter(p => 
   String(p).startsWith(this.searchText));
   this.filteredArray = this.filteredArray.slice(0, 21);
}

Afterward, I simply assigned the filtered Array as the datasource for the ng2-completer: [datasource]="filteredArray"

I hope this unconventional approach proves helpful to others facing similar challenges :)

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

Angular2 is throwing a TypeError, stating that OrbitControls is not a valid constructor

Currently, I am delving into the world of angular2 and three.js. Here is how my angular cli configuration looks like. Inside package.json: "three": "^0.81.2", "three-stl-loader": "^1.0.4", In the angular.cli.json: "../node_modules/three/build/thr ...

Dynamic divs to occupy the rest of the available vertical area

I have been experimenting with a new website layout and created a form setup. However, I am facing an issue with the fluidity of the layout. While the items are floating into position, there is a problem where if the item on the right is 400px bigger than ...

Hexagon in the Middle

I'm struggling to center these hexagons without them jumping up or down. I've tried searching online for solutions, but couldn't find anything that works. I found another hexagon style, but it didn't have any images so I couldn't u ...

Setting the z-index to place an absolutely positioned element below a relatively positioned one

I am currently facing a challenge where I need to position an element under another one that has already been relatively positioned. The blue box must remain relatively positioned due to specific constraints within the website development process. For bet ...

After a successful login, Angular will once again redirect the user to the login page

I successfully implemented the back-end using nest-js to handle authentication with mongo-db. Registration and login are working fine, but I face an issue after logging in with a successful result - when I refresh the page, it redirects me back to the logi ...

Struggling to make the background image appear full screen on the webpage despite implementing a script

Currently, I am in the process of developing a responsive landing page using Bootstrap 4 and I would like to implement a background that changes every few seconds. Although I have managed to make the images change dynamically, I am facing difficulties inco ...

What is the best way to combine two objects in Angular?

How can I merge objects in Angular 2? Object Response 1 0:Object 1:Object 2:Object 3:Object Object Response 2 0:Object 1:Object 2:Object 3:Object MyComponent Component resultdata :any=Array; fooddrinks_data_func(Defaultparams){ return this.Ci ...

Issue: npm encountered an error due to writing after reaching the end

I've encountered a problem while trying to install Cordova and Ionic. Due to what appears to be a corrupted installation, I had to uninstall NodeJS - Cordova - Ionic. After re-installing NodeJS successfully, the trouble began when running the pop ...

I am looking for a way to have one element as a child of another element without automatically adopting specific properties

https://i.sstatic.net/iuNB7.png <span id="priority-dot-open-menu"> <span id="priority-menu"> <span class="tooltip-top"></span> <span id="priority-dot-blue">& ...

Enforcing custom validation with Angular 2 upon keyup event

I am having trouble with the code below: this.form = fb.group({ username: ['', Validators.compose([Validators.required])], fullName: ['', Validators.compose([Validators.required])], password: ['', Vali ...

Ways to implement CSS in my JQuery Plugin

In the process of creating a unique JQuery component plugin that relies on some essential default CSS for its layout, I am faced with a dilemma. Should I: Create a separate .css file and load it dynamically within my plugin code (How would this be accomp ...

Detecting when the Chrome browser reloads with a mouse click using Typescript

In my Angular2 application, I am trying to identify when a user clicks the "reload this page" option in their browser. How can I detect this specific event in typescript without relying on keyboard inputs? So far, I have attempted the following approaches ...

Having difficulty connecting to the router within a container component for Angular2 routing

Presently, my code snippet looks like this: import { Router } from 'angular2/router'; @Component({...}) export class Index { constructor(public router: Router) { this.router.subscribe({...}); } } Although there are additional function ...

How can we avoid duplicating injectors in a child class when extending a class that already has injected services?

Delving deep into TypeScript inheritance, particularly in Angular 11, I've created a BasePageComponent to encompass all the necessary functions and services shared across pages. However, I've encountered an issue where my base class is becoming b ...

I need to style a blockquote so that it floats to the right, but I also want it to be

I want to enhance the appearance of my blockquotes by giving them a different color background and ensuring they stand out from the regular text. Although using float:right helps achieve this effect, I prefer not to force the blockquote to the right side o ...

I am looking to use jQuery to position a table at the top of the page

At the bottom of the page, there is a table that I would like to reposition to the very top so that it aligns with the top of the browser window (compatible with Internet Explorer and Firefox). What is the most effective method to achieve this? <div i ...

Issues with IE6 hover state not properly resetting

Tutorial This particular issue has been isolated in the test case provided above. It is easily noticeable when viewed in IE6. Description of the Issue In Internet Explorer 6, when hovering over the link, all child elements that are supposed to be visibl ...

Hover Effect in JavaScript

After thoroughly checking all the duplicates below, I still couldn't quite figure out how to achieve the desired effect. Here are some resources I looked into: make animation hover like transition hover JS hover-like animation Hover animation with js ...

Customizing the appearance of map items in a React JS application

As a newcomer to reactjs, I am working with an array that looks like this: const mediumNames = ["TAMIL Medium", "ENGLISH MEDIUM"] Using the above code, I have created two cards: const [selectedMediumColor, setSelectedMediumColor] = useState('') ...

Exploring resources within a library in Angular

I need help accessing assets from a shared library within my nx workspace. Here is the structure: /apps -- my-app // ... /libs -- shared -- assets -- resources -- translation.json The shared lib has an alias defined as @my-company/s ...