如果您不想使用formcontrol
方法,那麼可以通過減輕痛苦的方式來消除擊鍵。
search.component.html
<input type="text" placeholder="Enter a value" name="foo" [(ngModel)]="txtQuery" (ngModelChange)="onFieldChange($event)">
search.component.ts
export class SearchComponent {
txtQuery: string; // bind this to input with ngModel
txtQueryChanged: Subject<string> = new Subject<string>();
constructor() {
this.txtQueryChanged
.debounceTime(1000) // wait 1 sec after the last event before emitting last event
.distinctUntilChanged() // only emit if value is different from previous value
.subscribe(model => {
this.txtQuery = model;
// Call your function which calls API or do anything you would like do after a lag of 1 sec
this.getDataFromAPI(this.txtQuery);
});
}
onFieldChange(query:string){
this.txtQueryChanged.next(query);
}
}
分享你的代碼,你有ngModelChange做什麼? – Milad
https://angular.io/docs/ts/latest/tutorial/toh-pt6.html#!#search-by-name可能是這個鏈接會幫助你 – Devansh
要麼使用Devansh的建議,如果你的意圖是反彈一個'Observable'。否則,你可以爲'onFieldChange()'寫一個封裝器方法,它將消除它並在'ngModelChange()'中調用。 – naeramarth7