我正在使用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(???)"
。你如何建議我可以使這個自動填充更適合我的項目?