a blog for those who code

Thursday 1 November 2018

How I added AutoComplete TextBox in Angular App

As a beginner in AngularJS, I tried to create a AutoComplete Textbox which gets its data from the service and show in the frontend when you start typing. The code is very simple and easy to follow :

Service : Its a simple Get request where I am getting all the customers which are not deleted.

public async Task<IActionResult> Get()
  var customers = await _customerRepository.Query()
                      .Where(x => !x.IsDeleted)
  if (customers == null)
    return NotFound();
  return Json(customers);

Html : In this there are two things, one an input html field where we need to use ng-model (a field which will be used the .js file), ng-change (whenever there is any change in input it will call the function), autocomplete (to not use browser autocomplete dropdown). The other is a div which will show the results having ng-repeat (looping through users), ng-bind (which will bind the name of the user) and ng-click (when clicked on any item of dropdown it will select that)

<div class="form-group">
  <label class="col-sm-2 control-label">Customer</label>
  <div class="col-sm-10 search-user">
    <div class="input-group">
      <input name="name" ng-model="vm.fullName" ng-change="vm.filterValues()" 
             class="form-control" placeholder="Search user..." autocomplete="off" />
    <div id="search-results" ng-show="vm.focus">
      <div class="search-result" ng-repeat="user in vm.searchUsers" 
           ng-bind="user.fullName" ng-click="vm.setQuery(user.fullName)"></div>

JS : In the JS file just get the data from the service and store in vm.users. As you can see below two functions filterValues and setQuery which we have used before. FilterValues function will just filter the vm.users based on what you have searched whereas setQuery will set the User when clicked from the dropdown.

vm.filterValues = function () {
  if (vm.fullName.length >= 2) {
    vm.focus = true;
    vm.searchUsers = vm.users.filter(u => u.fullName.toLowerCase()
vm.setQuery = function (fullName) {
  vm.fullName = fullName;
  vm.focus = false;

The CSS used are as below

#search-results {
    width: 197px;
    max-height: 200px;
    border: 1px solid #dedede;
    border-radius: 3px;
    box-sizing: border-box;
    position: absolute;

.search-result {
    background: white;
    padding: 5px;
    .search-result:nth-child(even) {
        background: #aeaeae;

.search-user {
    position: relative;
    z-index: 10000;

Hope you able to understand how easy is to create a AutoComplete dropdown in Angular JS. Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a Comment