我正在使用ngx-bootstrap/typeahead在我的页面中创建一个自动完成。这是我目前使用的代码:在Angular Directive中包装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
的结构与typeaheadOnSelect($event)
中的ngx-bootstrap $event
不同。我也不知道如何处理(select)="mySelectFunction(???)"
。你如何建议我可以使这个自动填充更适合我的项目?