Claudiu Ungureanu
Claudiu Ungureanu

Reputation: 51

best practice for trigger a method by user's input in angular2

I have this scenario: expecting an user's input and use that to _http.get() from server. I have tried using keyup event, but can't manage. Any recommendation is much appreciated.

My template:

<div class="col-md-8">
   <input type="text" class="form-control" [(ngModel)]="workOrder" (keyup)="populate()" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>
</div>

My ts file:

populate(){
  console.log(this.workOrder);
  this._lookup.getIcrData().subscribe(res => {
    console.log(res);
  });
}

Upvotes: 3

Views: 271

Answers (3)

Prithivi Raj
Prithivi Raj

Reputation: 2736

Try RxJs, if you looking for a best practice. check this angular documentation Template

<input #searchBox type="text" class="form-control" [(ngModel)]="workOrder" (keyup)="populate(searchBox.value)" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>

Component

import { Component, OnInit } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { Subject }    from 'rxjs/Subject';
import { of }         from 'rxjs/observable/of';

import {
   debounceTime, distinctUntilChanged, switchMap
 } from 'rxjs/operators';

searchResult : Observable<any>;
private searchTerms = new Subject<string>();

ngOnInit(): void {
this.searchResult = this.searchTerms.pipe(
  // wait 300ms after each keystroke before considering the term
  debounceTime(300),

  // ignore new term if same as previous term
  distinctUntilChanged(),

  // switch to new search observable each time the term changes
  switchMap((term: string) =>   this._lookup.getIcrData(term)),
);
}

populate(term: string){
this.searchTerms.next(term);
}

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657967

ngModelChange is usually a good option

<input type="text" class="form-control" 
    [(ngModel)]="workOrder" 
    (ngModelChange)="populate()" 
    placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>

Upvotes: 1

Stefan Svrkota
Stefan Svrkota

Reputation: 50643

You are looking for ngModelChange:

<div class="col-md-8">
    <input type="text" class="form-control" [ngModel]="workOrder" (ngModelChange)="populate($event)" placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>
</div>

Component

populate(value: any){
  console.log(value);
  this._lookup.getIcrData().subscribe(res => {
        console.log(res);
  });
}

Upvotes: 3

Related Questions