Introduction
I have seen in some web crawlers and sites that while I am writing the initial two letters of a word, it demonstrates to me a recommended run down to choose. These auto finish content boxes are for the most part utilized as a part of ongoing tasks to expand client intuitiveness with the site. Presently in this post, we will take a gander at how this is executed in Angular4 using typescript.
For instance, we should discuss the Google auto finish look box.
Here, the proposed results will come in view of the past list items or most looked outcomes.
Executing Auto Complete Textbox in Angular
To execute an auto finish content box in Angular with a textbox, we need to create an angular application. In this application, I am getting the information recommendation from the service.
Here some references which can help you make and configure angular project:
- How To Create Angular App Using Angular CLI
- Getting Started With Angular 2 Using Visual Studio Code
- How To Post FormData To WebAPI Using Angular 2
- Angular CLI Official site
Steps to complete autocomplete textbox task are:
First of all, you need to install node.js and VS code on your system.
Create Angular application using angular CLI command ,If you are still facing issue to create simple hello world application with all configuration click here...
Follow some steps to create autocomplete textbox using angular
Step 1: Create ASP.NET WEBAPI to get data from database now i am getting clientList from api see code..
1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Net;
5. using System.Net.Http;
6. using System.Web.Http;
7.
8. namespace ApplicationAPI.Controllers
9. {
10.
11. [RoutePrefix("api/Client")]
12. public class ClientController : ApiController
13. {
14. MVCRSTechEntities _context = new MVCRSTechEntities();
15. [Route("GetClientList/term")]
16. public IHttpActionResult GetClientList(string term)
17. {
18. var clientList = from c in _context.Clients
19. where c.ClientName.Contains(term)
20. select c;
21. return Ok(clientList);
22. }
23. }
24. }
So now i am consuming endpoint http://localhost:52386/api/Client/GetClientList/term?term=a see image to output in json format.
If you don't want waste your time to create api and etc..just use this json to get client list according any string word.
save this json in your project name is Client.josn and set path inside http.get() method.
Client.Json
1. [
2. {
3. "ClientId": 11,
4. "ClientName": "Hytech Professionals"
5. },
6. {
7. "ClientId": 12,
8. "ClientName": "RVS IT Consulting"
9. },
10. {
11. "ClientId": 13,
12. "ClientName": "MCN Solution"
13. },
14. {
15. "ClientId": 24,
16. "ClientName": "C# Corner"
17. },
18. {
19. "ClientId": 27,
20. "ClientName": "Birla sunlife"
21. },
22. {
23. "ClientId": 28,
24. "ClientName": "Global Logic"
25. }
26. ]
Other wise you can use api to get data from database.Here both option are avilable you choose any api or directly json.
Step 2: Create angular application using Angular-CLI (ng new project_name) singe line of command.
Step 3: In angular default application replace app.component.html.see code below
src=>app=>app.component.html
1. <label class="col-sm-4 col-md-8 text-right control-label vertical-label" for="inputPassword3"> Select Client Name</label>
2. <div class="col-sm-8 col-md-4 text-right">
3. <div class="form-group">
4. <div class="input-group">
5. <input class="form-control" *ngIf="flag" type="text" [(ngModel)]="ClientName" (keyup)="searchClient(ClientName)" />
6. <input class="form-control" [(ngModel)]="ClientName" disabled *ngIf="!flag" type="text" />
7.
8. </div>
9. </div>
10. <div class="search-result" *ngIf="flag">
11. <ul>
12. <li *ngFor="let client of clients | async">
13. <a (click)="onselectClient(client)">{{client.ClientName}}</a>
14. </li>
15. </ul>
16. </div>
17.
18.
19. </div>
In HTML part, i have created a textbox and applied chnges to create autocomplete textbox accordingly.
Step 4: use app.component.ts to write logic, Just replace code from below code.
src=>app=>app.component.ts
1. import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
2. import { Observable, Subject } from 'rxjs';
3. import { ClientSearchService } from './_services/client-search.service';
4. @Component({
5. selector: 'client-search',
6. templateUrl: './app.component.html',
7. })
8. export class AppComponent implements OnInit {
9. public clients: Observable<any[]>;
10. private searchTerms = new Subject<string>();
11. public ClientName = '';
12. public flag: boolean = true;
13. constructor(
14. private clientSearchService: ClientSearchService,
15. ) {
16.
17. }
18.
19. ngOnInit(): void {
20. this.clients = this.searchTerms
21. .debounceTime(300) // wait for 300ms pause in events
22. .distinctUntilChanged() // ignore if next search term is same as previous
23. .switchMap(term => term // switch to new observable each time
24. // return the http search observable
25. ? this.clientSearchService.search(term)
26. // or the observable of empty heroes if no search term
27. : Observable.of<any[]>([]))
28. .catch(error => {
29. // TODO: real error handling
30. console.log(error);
31. return Observable.of<any[]>([]);
32. });
33. }
34. // Push a search term into the observable stream.
35. searchClient(term: string): void {
36. this.flag = true;
37. this.searchTerms.next(term);
38. }
39. onselectClient(ClientObj) {
40. if (ClientObj.ClientId != 0) {
41. this.ClientName = ClientObj.ClientName;
42. this.flag = false;
43. }
44. else {
45. return false;
46. }
47. }
48.
49. }
Step 5: Create service folder name is _services=>client-search.service.ts and inside this ts file write code to consume WebAPI.see code
src=>app=>_services=>client-search.service.ts
1. import { Injectable } from '@angular/core';
2. import { Http, Response } from '@angular/http';
3. import { Observable } from 'rxjs';
4. @Injectable()
5. export class ClientSearchService {
6. endPoint: string;
7. constructor(private http: Http) {
8. this.endPoint = "http://localhost:52386/api/Client/GetClientList/term";
9. }
10. search(term: string): Observable<any[]> {
11. var ClientList = this.http.get(this.endPoint + '?term=' + term)
12. .map((r: Response) => { return (r.json().length != 0 ? r.json() : [{ "ClientId": 0, "ClientName": "No Record Found" }]) as any[] });
13. return ClientList;
14. }
15. }
Step 6: Now need some chnages in app.module.ts,Need to register service in provider.see code.
src=>app=>app.module.ts
1. import { BrowserModule } from '@angular/platform-browser';
2. import { FormsModule } from '@angular/forms';
3. import { NgModule } from '@angular/core';
4. import { HttpModule } from '@angular/http';
5. import { ClientSearchService } from './_services/client-search.service';
6. import { AppComponent } from './app.component';
7.
8. @NgModule({
9. declarations: [
10. AppComponent
11. ],
12. imports: [
13. BrowserModule, FormsModule, HttpModule
14. ],
15. providers: [ClientSearchService],
16. bootstrap: [AppComponent]
17. })
18. export class AppModule { }
Step 7: To make more attractive use css,so copy this code and paste on index.html page.To add css file download project from this article.see code
src=>index.html
1. <!doctype html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <meta http-equiv="x-ua-compatible" content="ie=edge">
6. <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport" />
7. <!-- Bootstrap 3.3.6 -->
8. <link href="/assets/css/bootstrap.min.css" rel="stylesheet" />
9. <link href="/assets/css/custom.css" rel="stylesheet" />
10. <!-- Theme style -->
11. <link href="/assets/css/AdminLTE.css" rel="stylesheet" />
12. <!-- icon font -->
13. <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
14.
15. <link href="/assets/css/skins/_all-skins.min.css" rel="stylesheet" />
16. <link rel="shortcut icon" href="assets/img/favicon.ico">
17. <link rel="icon" type="image/gif" href="assets/img/animated_favicon1.gif">
18. </head>
19. <body>
20. <client-search></client-search>
21. </body>
22. </html>
You can se hetre on the index.html i am using component client-search as tag.
Step 8: I think all set to run application but be sure installed all packages from npm,If not use command "npm install" after npm install new folder will create in your root folder name is "node_module".
Step 9: Now we are ready to run application open terminal and run command "npm start" or "ng serve".
Step 10: Remember if chrome browser is not opening by default type http://localhost:4200/ See output in your browser like this.
Conclusion:
According to this image type, any word or character in the textbox result will show.Data is coming from database according to search word 's'.
I hope your application is working and i am sure you learned a simple trick to make textbox as auto-complete using angular and typescript.
If still, you are facing any error, issue download attached project.
You have just read an article that categorized by title Angular
by title Creating an autocomplete textbox in angular 4. You can bookmark this page with a URL https://bikeshsrivastava.blogspot.com/2017/09/part-50-creating-autocomplete-textbox.html. Thank You!
Author:
Bikesh Srivastava - Tuesday, September 5, 2017
Thank you.Well it was nice post and very helpful information on AngularJS5 Online Training Hyderabad
ReplyDeleteI like your blog, I read this blog please update more content on hacking,
ReplyDeleteNice post,and good information Thanks for sharing
further check it once at Dot NET Online Course