Angular 2 : How to limit the number of search results in ng2-completer?
As of now this is not possible from ng2-completer.
The better way to prevent more record is to send only 10 to 12 records from api.
I don't think ng2-completer
supports this feature right now.
But anyway, even if ng2-completer supports the feature, your data service should be the one responsible for maximum count of items. So just return first 10-20 items found, you don't want to return to client whole dataset. What if you find thousands or even more items?
If the user sees to many items, he understands, he must specify the search more precisely.
Edit: just have checked the CSS classes, you were close..for me this worked directly in the demo page..changed the styles of a page like this:
.completer-dropdown[_ngcontent-tsn-1] {
max-height: 200px !important;
overflow-y: scroll;
overflow-x: hidden;
...
}
See the image below:
It's doable, you just need to be aware that angular 2 uses view encapsulation and since ng2-completer
is a different component setting the styles without the /deep/
or >>>
selectors won't affect it.
To restrict the dropdown length you can specify the following styles in the component that contains it:
:host >>> .completer-dropdown {
overflow-y: auto;
max-height: 200px;
}
Another option is to filter the items before they are provided to ng2-completer this can be done by creating a custom CompleterData
and manipulating 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();
// Now we can slice/sort/change or manipulate the result in any way that we want
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 needed
}
public convertToItem(data: any): CompleterItem {
if (!data) {
return null;
}
// data will be string if an initial value is set
return {
title: typeof data === "string"? data : data.text
}
}
}
see plunk