I'm trying to create something like isTyping or not, so I have to detect when user stop type more or less 3 seconds, so I can do my stuff, I allready detected when he's typing using this :
ngOnChanges(searchValue: string) {
if (!this.searchChangeObserver) {
Observable.create(observer => {
this.searchChangeObserver = observer;
}).debounceTime(3000)
.subscribe((data) => {
if (data) {
typingStuff();
}
else {
notTypingStuff();
}
});
this.searchChangeObserver.next(searchValue);
}
}
}
So now I have to detect when user stops typing to do the notTypingStuff();
Is there a simple way to do it?
EDIT
I'm also using this :
constructor(){
this.modelChanged
.debounceTime(300)
.subscribe((data) => {
if (data) {
typingStuff();
}
else {
notTypingStuff();
}
});
}
But should know when user stops to type in 3 seconds to do the notTypingStuff()
as well..
One possible way is to attach a keyup event to the input element and send an HTTP request for each character entered to the server to fetch search results: const input = document. querySelector('#input-text'); // Listen for `keyup` event input.
step 1. set time out to null then clear the current timeout when the user is typing. step 2. trigger clear timeout to the variable define before keyup event is triggered.
You can use Angular event bindings to respond to any DOM event. Many DOM events are triggered by user input. Binding to these events provides a way to get input from the user. To bind to a DOM event, surround the DOM event name in parentheses and assign a quoted template statement to it.
Angular Version 6.
HTML:
<input matInput type="text" (keyup)="searchInterest()" [(ngModel)]="keyword" [matAutocomplete]="auto">
COMPONENT:
public searchInterest() {
let wordSearch = this.keyword;
setTimeout(() => {
if (wordSearch == this.keyword) {
if (this.keyword) {
//função que irá retornar sua lista de objetos
}else{
//code here
}
}
}, 2000);
}
For the not typing stuff you could create an observable from the input event and set the debaunce time:
HTML:
<input #yourElement [(ngModel)]="yourVar"/>
Component:
@ViewChild('yourElement') yourElement: ElementRef;
ngAfterViewInit() {
Observable.fromEvent(this.yourElement.nativeElement, 'input')
.map((event: Event) => (<HTMLInputElement>event.target).value)
.debounceTime(3000)
.distinctUntilChanged()
.subscribe(data => notTypingStuff());
}
This way your method will only be executed 3000 after the input is modified, or in other words after the user stops typing.
EDIT: Angular 9 w/ RxJS 6.5.4
ngAfterViewInit(): void {
fromEvent(this.yourElement.nativeElement, 'input')
.pipe(map((event: Event) => (event.target as HTMLInputElement).value))
.pipe(debounceTime(3000))
.pipe(distinctUntilChanged())
.subscribe(data => notTypingStuff());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With