EDIT
在Angular的新版本中,您可以使用ngModelOption
中的updateOn
来设置'blur'
.Link to angular.io documentation
代码示例:
<input [(ngModel)]="value"
[ngModelOptions]="{ updateOn: 'blur' }"
(ngModelChange)="updateOnlyOnBlur($event)">
LEGACY个
如果您不想使用formcontrol
方法,这里有一种不那么痛苦的解除击键的方法.
搜索组成部分html
<input type="text" placeholder="Enter a value" name="foo" [(ngModel)]="txtQuery" (ngModelChange)="onFieldChange($event)">
搜索组成部分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);
}
}