3

我正在使用 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.countryngx-bootstrap 进行绑定。看起来这$event与.$eventtypeaheadOnSelect($event)

我也不知道怎么处理(select)="mySelectFunction(???)"。您如何建议我可以使此自动完成功能对我的项目更具可重用性?

4

2 回答 2

1

您需要在父组件中包含 typeahead 组件标签,并将值传递给 typeahead 组件,该组件使用@Input装饰器获取值。我认为您需要了解 Angular 组件的一般工作原理,因为组件本身的设计方式是可以很容易地重复使用。

Typeahead 组件 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">

Typeahead 组件-

@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>
于 2017-09-16T04:30:50.663 回答
1

您可以扩展指令TypeaheadDirective本身并在其中设置所需的默认值。看看这个要点:https ://gist.github.com/francarmona/9e7d373e80e9cc9afb9c023923093c01

于 2018-10-01T10:02:47.660 回答