用户在angular2中输入触发方法的最佳实践

时间:2017-12-04 10:52:00

标签: angular event-handling user-input

我有这样的场景:期待用户的输入并将其用于来自服务器的_http.get()。 我尝试过使用keyup事件,但无法管理。任何建议都非常感谢。

我的模板:

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

我的ts档案:

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

3 个答案:

答案 0 :(得分:3)

您正在寻找ngModelChange

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

<强>组件

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

答案 1 :(得分:1)

ngModelChange通常是个不错的选择

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

答案 2 :(得分:1)

如果您正在寻找最佳实践,请尝试使用RxJs。 check this angular documentation 模板

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

组件

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