2017-07-31 82 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>