ng2-semantic-ui search/select with ajax lookup

The Error

When using ng2-semantic-ui select or search components, the lookup function cannot find the service and always returns 0 results.

https://edcarroll.github.io/ng2-semantic-ui/#/modules/search
https://edcarroll.github.io/ng2-semantic-ui/#/modules/select


ERROR TypeError: Cannot read property 'dataService' of undefined

The docs say to use an arrow function to allow this.

optionsLookup  (query:string, initial?:U) => Promise<t[]>
A function to asynchronously transform the provided query string into the array of options. Must return a Promise. This must be defined as an arrow function in your class.</t[]>

The optionsLookup function needs to be an arrow function instead of part of the class because of the way ng2-semantic-ui scoped the function variable.

// autocomplete.component.ts
    optionsSearch (query: string)  {
        return new Promise((resolve, reject) => {
            this.dataService.getAutocompleteData({
                search: query
            }).subscribe(res => {
                resolve(res.results);
            });
        });
    }

The above code should be changed to this to allow it to work.

// autocomplete.component.ts
    optionsSearch = (query: string) => {
        return new Promise((resolve, reject) => {
            this.dataService.getAutocompleteData({
                search: query
            }).subscribe(res => {
                resolve(res.results);
            });
        });
    }
Share this:

Leave a comment

3 × 1 =