Вы можете добавить debounceTime
в свой FormControl.
Например:
...
Component({
selector: 'my-app',
template: `<input type=text [value]="firstName" [formControl]="firstNameControl">
<br>{{firstName}}`
})
export class AppComponent {
firstName = 'Name';
firstNameControl = new FormControl();
formCtrlSub: Subscription;
ngOnInit() {
// debounce keystroke events
this.formCtrlSub = this.firstNameControl.valueChanges
.debounceTime(1000)
.subscribe(newValue => this.firstName = newValue);
...
или вы можете использовать fromEvent
export class HelloComponent implements OnInit, OnDestroy {
@Input() name: string;
@ViewChild("editor") editor: ElementRef;
subscription: Subscription;
ngOnInit() {
this.subscription = fromEvent(this.editor.nativeElement, "keyup").pipe(
map(event => this.editor.nativeElement.value),
debounceTime(1000)
).subscribe(val => this.name = val);
}
<form>
<input type="text" #editor name="hello">
</form>
См. Прикрепленный Stackblitz
или вы связываете ngModelChange
с наблюдаемой и используете debounceTime
с ним:
<hello name="{{ name }}"></hello>
<input class="form-control" [(ngModel)]="userQuestion"
type="text" name="userQuestion" id="userQuestions"
(ngModelChange)="this.userQuestionUpdate.next($event)">
<ul>
<li *ngFor="let message of consoleMessages">{{message}}</li>
</ul>
export class AppComponent {
name = 'Angular 6';
public consoleMessages: string[] = [];
public userQuestion: string;
userQuestionUpdate = new Subject<string>();
constructor() {
// Debounce search.
this.userQuestionUpdate.pipe(
debounceTime(400),
distinctUntilChanged())
.subscribe(value => {
this.consoleMessages.push(value);
});
}
}
См. Stackblitz2
Редактировать:
Дополнительно вы можете найти пример в официальной документации Angular для Практическое наблюдаемое использование (где используется debounceTime
).
import { fromEvent } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { debounceTime, distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators';
const searchBox = document.getElementById('search-box');
const typeahead = fromEvent(searchBox, 'input').pipe(
map((e: KeyboardEvent) => (e.target as HTMLInputElement).value),
filter(text => text.length > 2),
debounceTime(10),
distinctUntilChanged(),
switchMap(() => ajax('/api/endpoint'))
);
typeahead.subscribe(data => {
// Handle the data from the API
});