我有这种情况:期望用户的输入,并将其从服务器中使用为_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);
});
}
您正在寻找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);
});
}
ngModelChange
通常是一个不错的选择
<input type="text" class="form-control"
[(ngModel)]="workOrder"
(ngModelChange)="populate()"
placeholder="{{ 'FIELDS.PMS_IFR_WO' | translate }}"/>
如果您寻找最佳练习,请尝试RXJS。检查此角文档模板
<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);
}