2

I Have a angular6 app with a simple input tag:

<input type="text" name="searchBox" [(ngModel)]="searchTerm" class="form-control" />

I would like to make a observable of the searchTerm property to add some operators like debounce, etc ,etc.

How can I do that ( Without using the ReactiveForms ) ?

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
gog
  • 11,788
  • 23
  • 67
  • 129
  • Possible duplicate of [Angular and debounce](https://stackoverflow.com/questions/32051273/angular-and-debounce) – Krypt1 May 17 '18 at 13:16

1 Answers1

5

There are a few ways you can accomplish this. The easiest I've found is as follows:

Template should contain:

<input
  #searchInput
  [(ngModel)]="searchTerm"
  type="text"
  (keyup)="onChange(searchInput.value)" />

Component should have:

  import { Subject } from 'rxjs';
  import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

  @Output() inputChanged: EventEmitter<string> = new EventEmitter<string>();
  input = new Subject<string>();

  constructor() {
    this.input
        .pipe(debounceTime(300))
        .pipe(distinctUntilChanged())
        .subscribe(input => this.emitInputChanged(input));
  }

  onChange(input: string) {
     this.input.next(input);
  }

The Subject is subscribable. You can pipe in your other functions(like debounce) and then can emit changes from it at the end of the chain. I don't know what you are using the ngModel for, but since you have it in your question I left it. Any component that is listening to the output of inputChanged will get the updated value after the debounce occurs.

peinearydevelopment
  • 11,042
  • 5
  • 48
  • 76