简体   繁体   中英

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);
  });
}

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);
  });
}

ngModelChange is usually a good option

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM