Monday, November 20, 2017

AutoCompletion Search Box filtering data from a remote api using Angular 2

Getting Started

For this example I am going to use ngui which is collection of quality Angular2 directives.

To make ngui available to your project, you need to install a npm package "@ngui/ngui".

NPM Install

$ npm install @ngui/ngui --save

systemjs.config.js

map: {
  app: "app",
  ...

'@ngui/auto-complete':'node_modules/@ngui/auto-complete/dist/auto-complete.umd.js',
},

Import and include directives for your application

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
import { FormsModule }  from '@angular/forms';
import { NguiAutoCompleteModule } from '@ngui/auto-complete';
import { HttpModule }      from '@angular/http';


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

app.component.ts

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

import { GetAPIs} from './getAPIS';


enableProdMode();

After importing all the modules as explained above, refer below sample codes which are cretaed inorder to create a simple auto completion search box which can filter data from a remote resource using HTTP calls.

app.component.ts

import { Component,enableProdMode } from '@angular/core';
import { GetAPIs} from './getAPIS';

enableProdMode();

@Component({
  selector: 'my-app',
  template: `<input ngui-auto-complete
  id="model4"
  [(ngModel)]="model4"
  placeholder="Enter the API(min. 2 chars)"
  [source]="arrayOfStrings"
  path-to-data="results"
  min-chars="2" />
<br/>selected api: {{model4 | json}}<br/><br/>`,
providers: [GetAPIs]
})
export class AppComponent {

  model1: any;
  arrayOfStrings: string[];
  //apis:{};
  constructor(private getAPIs: GetAPIs) {
    this.getAPIs.getAPIDetails().subscribe(arrayOfStrings => {this.arrayOfStrings=arrayOfStrings;});

  }

 
 }

getAPIS.ts (this class is the service class which calls the remote api using http calls and return the data to app.component.ts)

import {Injectable} from '@angular/core';
import {Http,Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class GetAPIs{


    constructor(private http:Http)
    {
    }
getAPIDetails()
{

    return this.http.get('http://www.mocky.io/v2/5a12bd962c0000ba1dace740').map((res:Response)=>res.json());
}

    }


That's all you need to configure. Run the server, then you can see a similar search box as following.




Blogger Widgets