Wrap ngx-bootstrap/typeahead in an Angular Directive

Viewed 1200

I'm using ngx-bootstrap/typeahead to have an autocomplete in my page. This is the code that I'm currently using:

<input type="text" class="form-control" name="countryName" autocomplete="off" [(ngModel)]="asyncSelected" (blur)="typeaheadOnBlur()" [typeahead]="countryDataSource" (typeaheadOnSelect)="typeaheadOnSelect($event)" typeaheadWaitMs="300" typeaheadOptionField="name">

Component:

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() returns an array of objects (observable) in the following format:

[{id: 1, name: "Australia", code: "AU"}, {id: 2, name: "United States", code: "US"}, ...]

Now, I think the code in my component does not belong to the component that is just using autocomplete. It also does not make it reusable that much. I don't want to have all these codes in the component and all those (blur)="typeaheadOnBlur()", typeaheadWaitMs="300" every time that I want to use my auto complete I'm thinking of creating a directive to use it as follows:

<input [myAutoComplete] [ngModel]="viewModel.nestedProperty?.country" (NgModelChange)="viewModel.nestedProperty.country=$event" (select)="mySelectFunction(???)" />

As you might have noticed, I couldn't use viewModel.nestedProperty.country for my binding with ngx-bootstrap. Looks like that this $event has different structure than ngx-bootstrap $event in the typeaheadOnSelect($event).

I also don't know how to handle (select)="mySelectFunction(???)". How do you suggest I can make this autocomplete more reusable for my project?

2 Answers
Related