Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Aurelia Typeahead
<!-- See for details on prepare-query -->
style="display: inline-block"
hinttext="Type a..."
<require from="../../css/typeaheadjs.css"></require>
<div class="form-group">
<label if.bind="!!labeltext" for="${inputId}">${labeltext}</label>
<input type="text" id="${inputId}" class="form-control" placeholder="${hinttext}" spellcheck="off" autocomplete="off"></input>
import { customElement, bindable, bindingMode, autoinject } from 'aurelia-framework';
import 'jquery';
import 'Bloodhound';
import 'typeahead';
let nextId = 1;
export class TypeAhead
@bindable prepareQuery: Function;
@bindable onSelect: Function;
@bindable hinttext: string;
@bindable labeltext: string;
@bindable({ defaultBindingMode: bindingMode.oneWay }) initialValue: any;
private inputId = "ta-" + nextId++;
private suggestionEngine: Bloodhound<any>;
private typeahead: JQuery;
constructor(private element: Element) {
this.suggestionEngine = new Bloodhound<any>({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'http://set-by-interceptor',
prepare: (query, settings) => this.prepareQuery(query, settings),
rateLimitWait: 500 //ms
attached() {
let options: Twitter.Typeahead.Options = { minLength: 2 };
let dataset: Twitter.Typeahead.Dataset<any> = {
source: this.suggestionEngine,
async: true,
limit: 10, // needs to be same as whatever is fetched by api
display: res =>
let ele = jQuery(this.element).find("input");
this.typeahead = ele.typeahead(options, [dataset]);
this.typeahead.on('typeahead:select', (ev, suggestion) => {
this.onSelect({ suggestion: suggestion });
initialValueChanged() {
private setValue(valueObj) {
if(!this.typeahead) return;
let value = valueObj && ? : "";
var typeaheadInput ='ttTypeahead').input;
// Typeahead doesn't seem to fully sync objects (
// so we just set the display correctly. This relies on the assumption that the underlying value for this field
// is being stored in the class using typeahead, and updated via the onSelect below. In effect, if the user doesn't
// change anything the UI will appear to be right and the backing field will be unchanged, and if they do change
// something then the normal process for onSelect() will apply and return a full object.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.