0

I am trying to make autocomplete form with angular.

My component.html page

<form method="post" [formGroup]="uploadForm" >
        <div class="form-group">
          <label for="sem">Select Semester</label>
          <input type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="search"  formControlName="branch" id="sem" placeholder="Branch Name">
        </div>
        <button type="submit" [disabled]="" class="btn btn-primary">Submit</button>
</form>

and my component.ts page which i get from typeahead examples

  uploadForm: FormGroup;

  constructor(private formBuilder: FormBuilder, private userService: UserService) { }

  ngOnInit() {
     this.search = (text$: Observable<string>) => text$.pipe(
        distinctUntilChanged(),
         map(term => term.length < 2 ? []
           : this.result.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
       );
     }

and my user.service.ts is

branchData(branchData) {
    return this.http.post<DataResponse>('/user/branchSearch', branchData);
  }

The data will come from server, so for every word type in input field , query will be send to the server that will return the array something like this

[
   {
      _id: "1",
      branch: "A" 
    },
   {
      _id: "2",
      branch: "B" 
    },
   ]

and that branch will shows on dropdown.

So how will I send every typed word query to server and then show the result in dropdown.

2
  • 1
    Here is a good component is written for angular based bootstrap. try this https://ng-bootstrap.github.io/#/components/typeahead/examples Commented Aug 5, 2018 at 17:00
  • @Rohit.007 But then how to send and get the Value of autocomplete search for my nodejs server. Commented Aug 5, 2018 at 18:55

3 Answers 3

2

You can try like this.

<form method="post" [formGroup]="uploadForm">
      <div class="form-group">
          <label for="sem">Select Semester</label>
          <input type="text" class="form-control" [formControlName]="branch" id="sem" placeholder="Branch Name">
      </div>
      <button type="submit" [disabled]="" class="btn btn-primary">Submit</button>
</form>



uploadForm: FormGroup;
private searchSubscribe;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.uploadForm = this.formBuilder.group({
      branch: [null, Validators.required]
    });

this.searchSubscribe = this.uploadForm
  .get('branch')
  .valueChanges.debounceTime(400)
  .distinctUntilChanged()
  .subscribe(value => {
    value = value.toLowerCase();
    // process the search data
  });

  }
Sign up to request clarification or add additional context in comments.

2 Comments

And what is this contactChangeSubscribe
It works fine, Now how to show dropdown to input text field
2

So for your dropdow with input text field , NgBootsrap TypeHead the one which opens on focus

<label for="typeahead-focus">Search for a state:</label>
<input
  id="typeahead-focus"
  type="text"
  class="form-control"
  [(ngModel)]="model"
  [ngbTypeahead]="search"
  (focus)="focus$.next($event.target.value)"
  (click)="click$.next($event.target.value)"
  #instance="ngbTypeahead"
/>
<hr>
<pre>Model: {{ model | json }}</pre>

4 Comments

Then How to send the data to nodejs server?
On the click inside the function subscribe to an angular service which inturns calls your nose endpoint of post the model defined here contains the value of what you type , $event.target.value is the selected value which you can pass on as the payload within your service
For getting the values from the server you have to p the model within the {{}} in the pre tag from your service which should be subscribed on the ngOninit of the component , that calls your node get endpoint @Rupesh
Please check, I have edited My Query about what I want.
1

You can refer to the example given by Angular-Bootstrap, Here the state is hardcode but instead of hardcoding, you can fetch those elements by service. On each change method you can fetch the data from service and on service response, you can reinitialize the autocomplete variable.

import {Component} from '@angular/core';
import {Observable} from 'rxjs';
import {debounceTime, distinctUntilChanged, map} from 'rxjs/operators';

const states = ['Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado',
  'Connecticut', 'Delaware', 'District Of Columbia', 'Federated States Of Micronesia', 'Florida', 'Georgia',
  'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine',
  'Marshall Islands', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana',
  'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
  'Northern Mariana Islands', 'Ohio', 'Oklahoma', 'Oregon', 'Palau', 'Pennsylvania', 'Puerto Rico', 'Rhode Island',
  'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Islands', 'Virginia',
  'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];

@Component({
  selector: 'ngbd-typeahead-basic',
  templateUrl: './typeahead-basic.html',
  styles: [`.form-control { width: 300px; }`]
})
export class NgbdTypeaheadBasic {
  public model: any;

  search = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term.length < 2 ? []
        : states.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
    );

}

10 Comments

Do you know how to make the HTTP request in angular?
yes, I am sending post request but when I am consoling req.body on nodejs it shows { }.
have you tested the node service independently i.e. on browser or on postman?
But I don't know why in this case it is sending empty object as a data.
Have you checked the network tab for empty data on requested service?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.