how do I debounce the @Output of an inner component?

To debounce values you could use a Subject. A subject is both an observable and a observer. This means you can treat it as an observable and pass values to it as well.

You could leverage this to pass the new values from the inner-component to it and debounce it this way.

export class DebouncedComponent {
  @Output() outerValueChanged: new EventEmitter<string>();
  const debouncer: Subject<string> = new Subject<string>();

  constructor() {
      // you listen to values here which are debounced
      // on every value, you call the outer component
      debouncer
        .debounceTime(100)
        .subscribe((value) => this.outerValuedChanged.emit(value));
  }

  onInnerChange(value) {
    // send every value from the inner to the subject
    debouncer.next(value);
  }
}

This is untested pseudo-code. You can see a working example of the concept here (http://jsbin.com/bexiqeq/15/edit?js,console). It’s without angular but the concept remains the same.


Update: For newer versions of Angular you might need a slight: change debouncer.debounceTime(100) gets changed to debouncer.pipe(debounceTime(100))

constructor() {
      // you listen to values here which are debounced
     // on every value, you call the outer component
     debouncer
       .pipe(debounceTime(100))
       .subscribe((value) => this.outerValuedChanged.emit(value));
}

Leave a Comment

tech