我正在使用 ngx-bootstrap/typeahead 在我的页面中进行自动完成。这是我目前正在使用的代码:
<input type="text" class="form-control" name="countryName" autocomplete="off" [(ngModel)]="asyncSelected" (blur)="typeaheadOnBlur()" [typeahead]="countryDataSource" (typeaheadOnSelect)="typeaheadOnSelect($event)" typeaheadWaitMs="300" typeaheadOptionField="name">
零件:
asyncSelected: string;
constructor() {
this.countryDataSource = Observable.create((observer: any) => {
observer.next(this.asyncSelected);
}).mergeMap((input: string) => this.getAutoCompleteResults(input));
}
typeaheadOnSelect(event: TypeaheadMatch): void {
viewModel.nestedProperty.country = event.item.name;
viewModel.nestedProperty.countryCode = event.item.countryCode;
}
typeaheadOnBlur(): void {
viewModel.nestedProperty.country = asyncSelected;
}
getAutoCompleteResults()
以下列格式返回一个对象数组(可观察的):
[{id: 1, name: "Australia", code: "AU"}, {id: 2, name: "United States", code: "US"}, ...]
现在,我认为我的组件中的代码不属于仅使用自动完成功能的组件。它也不会使其可重复使用那么多。我不想在组件和所有这些代码中包含所有这些代码(blur)="typeaheadOnBlur()"
,typeaheadWaitMs="300"
每次我想使用我的自动完成时,我都在考虑创建一个指令来使用它,如下所示:
<input [myAutoComplete] [ngModel]="viewModel.nestedProperty?.country" (NgModelChange)="viewModel.nestedProperty.country=$event" (select)="mySelectFunction(???)" />
您可能已经注意到,我无法使用viewModel.nestedProperty.country
ngx-bootstrap 进行绑定。看起来这$event
与.$event
typeaheadOnSelect($event)
我也不知道怎么处理(select)="mySelectFunction(???)"
。您如何建议我可以使此自动完成功能对我的项目更具可重用性?