5

I have an input field where a user can search different user in my app. But I want to make a search in such a way that when the user types in the input it should simultaneously search. I have implemented my fuction which calls my back-end but i just want to know how can i send the value of input field with every keystroke. Please help

1
  • 1
    Show us what you have tried so far so we can give you some pointers :) Commented Jan 1, 2018 at 15:50

3 Answers 3

9

You should handle the ngModelChange Angular event (see this stackblitz). It takes into account any kind of change in the input field (key strokes, cut/paste with context menu, etc.), and ignores key strokes that do not result in an actual change (e.g. pressing and releasing Shift by itself does not trigger ngModelChange).

<input [ngModel]="searchStr" (ngModelChange)="modelChange($event)" />
import { Component } from "@angular/core";
import { FormsModule } from "@angular/forms";

@Component({
})
export class AppComponent {
  public searchStr: string = "";

  public modelChange(str: string): void {
    this.searchStr = str;
    // Add code for searching here
  }
}
Sign up to request clarification or add additional context in comments.

Comments

5

Use (keyup) event on your input and pass the ngModel value to your service

<input   #term (keyup)="search(term.value)" type="text" class="form-control search-text-indent  searchbar-positioning" >

and in component.ts

search(term: string): void {
   //pass it to your service     
}

Comments

1

I would use a form control to expose the valueChanges observable. This observable emits every time the value of the form control changes.

<input [formControl]="search">

This allows you to control the flow of the typeahead search

// component.ts
ngOnInit(){
    this.search.valueChanges
        .pipe(
            // debounce input for 400 milliseconds
            debounceTime(400),
            // only emit if emission is different from previous emission
            distinctUntilChanged(),
            // switch map api call. This will cause previous api call to be ignored if it is still running when new emission comes along
            switchMap(res => this.getSearchData(res))
        )
        .subscribe(res => {
            this.result = res;
        })
}

With this, you are controlling how often the api call gets called (debounceTime & distinctUntilChanged) and ensuring the order of which the api calls finish (switchMap). Here is a stack blitz demoing this.

Comments

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.