lliance
lliance

Reputation: 47

Angular make request on key Press

How to make an HTTP request on keypress event with the input, for now, I'm getting undefines as a result.

code below

app.component.html

<input
  id="search"
  type="text"
  placeholder=" search"
  value=""
  (keyup.enter)="searchData()"
  name="search"
/>

app.component.ts

  searchData(value: string) {

    this.results = this.googleService.getGoogle(value)
      .subscribe(x => {

        this.Data = x.items;
        console.log('Data', this.Data);
      }
  }

Upvotes: 1

Views: 1398

Answers (4)

Adrita Sharma
Adrita Sharma

Reputation: 22213

You can add [(ngModel)]="search"

Try like this:

 <input id="search" type="text" placeholder=" search" 
           [(ngModel)]="search" (keyup.enter)="searchData(search)" name="search" />

.ts

searchData(value: string) {
   this.results = this.googleService.getGoogle(value)
    .subscribe(x = > { this.Data = x.items;
     console.log('Data', this.Data);
}

Working Demo

Upvotes: 1

Maihan Nijat
Maihan Nijat

Reputation: 9344

Pass the entered value from the event target:

<input id="search" type="text" placeholder=" search" value=""
            (keyup.enter)="searchData($event.target.value)" name="search" />

And check if the value exists before making a call:

searchData(value: string) {
  if (!value) {
    return;
  }

  this.results = this.googleService.getGoogle(value)
     .subscribe(x => {
       this.Data = x.items;
       console.log('Data', this.Data);
 }

Upvotes: 1

German Quinteros
German Quinteros

Reputation: 1930

You forgot to add the input value as parameter of the function searchData

Check how to do that in the Angular documentation:

https://angular.io/guide/user-input#key-event-filtering-with-keyenter

With that approach, you should modify your code as follow:

app.component.html

 <input #inputField id="search" type="text" placeholder=" search" value=""
            (keyup.enter)="searchData(inputField.value)" name="search" />

app.component.ts

    searchData(value:string) { 
        this.results = this.googleService.getGoogle(value)
        .subscribe(x = > { this.Data = x.items;
         console.log('Data', this.Data);
    }

Check that we pass the value of the input to the function searchData through template references: https://angular.io/guide/user-input#get-user-input-from-a-template-reference-variable

Upvotes: 2

Armen Stepanyan
Armen Stepanyan

Reputation: 1848

You can create local variable and pass input value to your function.

<input
  #inputEl
  id="search"
  type="text"
  placeholder=" search"
  value=""
  (keyup.enter)="searchData(inputEl.value)"
  name="search"      
/>

Now you can see input value in searchData function

Upvotes: 1

Related Questions