Skip to main content

Getting started with ng2-combobox

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 4 min read
Stephan Hochdörfer

Since the first release of our ng2-combobox components for Angular the repository is still lacking a decent documentation on how to use the component if you are not that familiar with Angular. This blog post should give you some insights on how to set up the combobox component in an Angular application. If you haven't yet set up an Angular application yourself it is as simple as typing the following command:

ng new ng2-combobox-demo

To install the ng2-combobox component run the following command:

npm i ng2-combobox

To make your application aware of the ng2-combobox component edit src/app/app.module.ts and add an import statement for the ComboBoxModule module. Also add the module to the list of module imports:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ComboBoxModule } from 'ng2-combobox';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ComboBoxModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

The easiest way to get started with ng2-combobox is to make use of the local storage configuration, that way ng2-combobox will not talk to a remote resource but use a local variable as its datasource. Simply add a new variable to hold the records in your AppComponent and initialize it with the data that should be shown in the combobox:

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
local_types;

ngOnInit() {
this.local_types = [];
this.local_types[0] = {'name': 'Stephan', 'value': 'stephan'};
this.local_types[1] = {'name': 'Philipp', 'value': 'philipp'};
this.local_types[2] = {'name': 'Felix', 'value': 'felix'};
this.local_types[3] = {'name': 'Chris', 'value': 'chris'};
}
}

In the template - e.g. src/app/app.component.html - add the combo-box element:

<combo-box [listData]="local_types" [displayField]="'name'"
[valueField]="'value'"></combo-box>

The listData attribute points to the datasource - the variable we defined in the previous step. The displayField and valueField attributes define the keys holding the respective data. Open your browser, point it to the application and check if everything is working fine.

Using a local datasource is fun, but it is even more fun to let the ng2-combobox component interact with your api as a remote datasource. The ng2-combobox component does not limit you in any way, you can freely choose how to interact with your api, you just need to implement one method that handles the communication part. For the next examples we will use @angular/http and interact with a rest-ish api.

In case your application does not already use the @angular/http component, add it to your src/app/app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ComboBoxModule } from 'ng2-combobox';
import { HttpModule } from '@angular/http';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ComboBoxModule,
HttpModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

In our AppComponent class the Http dependency is needed to be able to fetch the data from the api. The data is fetched and assigned to a new local variable called remote_types. Additionally, we must define an onQuery method which is called by the ng2-combobox component once the user starts typing.

import { Component, OnInit } from '@angular/core';
import {Http} from '@angular/http';
import {Subject} from "rxjs";

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
remote_types;

constructor(private http: Http) {
}

ngOnInit() {
this.remote_types = <Subject>new Subject();
}

onQuery(query) {
let observable;

observable = this.http.post(
'http://localhost:8080/',
{'q': query}).map((res) => {
return res.json();
});

observable.subscribe((result) => {
if (false === result.success) {
result = [];
}
this.remote_types.next(result);
});
}
}

The onQuery method receives the string the user typed in as an argument and passes it to the api. To be notified once the server sent the data, we simply need to subscribe to the observable and once we get some data back the remote_types variable gets populated. In your template - e.g. src/app/app.component.html - the combo-box element declaration reflects the changes made above.

<combo-box [remote]="true" [listData]="remote_types"
[displayField]="'name'" [valueField]="'value'"
(onQuery)="onQuery($event)"></combo-box>

The remote attribute indicates that a remote datasource is used, the onQuery event defines that the onQuery method gets called and the current input is passed to it as a parameter.

The documentation in the ng2-combobox GitHub repo contains a list of different configuration options as well as events that can be subscribed to. For some more information on how to set up an Angular project use this sitepoint tutorial as a starting point.