2017-07-31 84 views
1

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

回答

0

您需要在父組件中包含typeahead組件標籤,並將值傳遞給使用@Input裝飾器獲取值的typeahead組件。我認爲您需要知道Angular組件如何工作,因爲組件本身是在這樣可以輕鬆地重複使用。

組分事先鍵入的內容HTML-

<input [id]="id" [(ngModel)]="_model" [typeahead]="workflows" (typeaheadLoading)="changeTypeaheadLoading($event)" 
(typeaheadNoResults)="TypeaheadNoResults($event)" (typeaheadOnBlur)="onBlurFunction($event)" 
[typeaheadMinLength]="MinLength" [typeaheadOptionsLimit]="OptionsLimit" 
[typeaheadOptionField]="OptionsField" [optionsListTemplate]="customListTemplate"> 

事先鍵入的內容成分 -

@Component({ 
selector: 'app-input-typeahead', 
templateUrl: './input-typeahead.component.html', 
}) 
export class InputTypeaheadComponent{ 
@Input() selected: any; 
@Input() workflows: any; 
... 
@Input() callback: Function; 
...} 

父組件

<app-input-typeahead name="requestTypeahead" [id]="workflowId" 
[label]="workflowLabel" [(ngModel)]="selectedWorkflow" [workflows]="requestMatrixList" 
[OptionsField]="optionsField"[OptionsLimit]="optionsLimit" [MinLength]="minLength" 
[customListTemplate]="customListTemplate" [customItemTemplate]="customItemTemplate" 
[placeholder]="placeholder" [callback]="onTypeaheadHandler"></app-input-typeahead>