我在Angular2应用程序中使用了ofer的自动完成功能
https://github.com/oferh/ng2-completer
我想要一种行为,其中自动完成不会在键入时自动打开,但我需要按一个按钮,然后只有当自动完成发出服务器请求并显示下拉列表时我试图实现CompleterData:
import { Http, Response } from "@angular/http";
import { Subject } from "rxjs/Subject";
import { HttpClient } from './shared';
import { CompleterData, CompleterItem } from 'ng2-completer';
export class AddressData extends Subject<CompleterItem[]> implements CompleterData {
private url: string;
constructor(private http: HttpClient, public erpIDParent: number, url: string) {
super();
this.url = url;
}
public setErpIDParent(erpIDParent: number) {
this.erpIDParent = erpIDParent;
}
public search(term: string): void {
console.log('searching');
if (this.erpIDParent > 0) {
this.http.get(`${this.url}${term}&erpIDParent=${this.erpIDParent}`)
.map((res: Response) => {
// Convert the result to CompleterItem[]
let data = res.json();
let matches: CompleterItem[] = data.map((address: any) => {
return {
originalObject: address,
title: address.Name
}
});
console.log(matches);
this.next(matches);
})
.subscribe();
}
}
public cancel() {
// Handle cancel
}
}
并将minSearchLength保持为1000
<ng2-completer placeholder="{{ 'NewOrder.typeToSearch' | translate }}" formControlName="address" [(ngModel)]="address" [datasource]="addressDataService" (selected)="addressSelected($event)" [minSearchLength]="1000"></ng2-completer>
所以它不会发送服务器请求然后点击我的按钮我有这个代码:
searchAddresses() {
this.addressDataService.search(this.address);
}
所以它会手动启动搜索,但似乎没有按照我想要的方式工作。下拉列表即时显示和隐藏。有什么方法可以解决这个问题吗?
答案 0 :(得分:1)
有一种方法,虽然它是一种解决方法,但不确定最终结果是否足够好。
您需要一个可以处理搜索的自定义CompleterData
组件,这将为您提供一种控制何时执行搜索的方法:
export class CustomData extends Subject<CompleterItem[]> implements CompleterData {
public doSearch = false;
constructor(private http: Http) {
super();
}
public search(term: string): void {
if (this.doSearch) {
this.http.get("http://example.com?term=" + term)
.map((res: Response) => {
// Convert the result to CompleterItem[]
let data = res.json();
let matches: CompleterItem[] = data.map((item: any) => this.convertToItem(item));
this.next(matches);
})
.subscribe();
} else {
// if we don't do the search return empty results
this.next([]);
}
}
}
由于调用了搜索,我们需要阻止显示搜索而不显示结果文字,因此我们将textSearching
和textNoResults
设置为false
<ng2-completer #completer [(ngModel)]="searchStr" [datasource]="datasource" [minSearchLength]="0" [textNoResults]="false" [textSearching]="false"></ng2-completer>
现在,当您想要进行搜索时,可以在数据提供者上设置doSearch
,它将开始工作。
最后一部分是将焦点设置回完成者并在激活时再次进行搜索:
组件中的:
@ViewChild("completer") private completer: CompleterCmp;
protected startSearch() {
this.datasource.doSearch = true;
this.completer.focus();
this.datasource.search(this.searchStr);
}
这是一个plunker example