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

后端 未结 2 840
闹比i
闹比i 2020-12-15 03:30

I have a component that wraps another component and binds to the InnerComponent.innerChanged() custom event. I want to bubb

2条回答
  •  时光取名叫无心
    2020-12-15 04:21

    Here is a working example Class with all needed imports, Angular 4+, TypeScript and tslint-friendly :) thought it might help some people looking for what I was looking moments ago!

    import { Component, Input, Output, EventEmitter, ViewChild, OnDestroy } from '@angular/core';
    import { Subject } from 'rxjs/Subject';
    import { Subscription } from 'rxjs/Subscription';
    import 'rxjs/add/operator/debounceTime';
    
    @Component({
      selector: 'app-searchbox',
      template: `
        
      `
    })
    export class SearchboxComponent implements OnDestroy {
      @Input() debounceTime = 500;
      @Output() change = new EventEmitter();
    
      query = '';
      placeholder = 'Search...';
      results;
    
      debouncer = new Subject();
      subs = new Array();
    
      constructor() {
        this.subs.push(this.debouncer.debounceTime(this.debounceTime).subscribe(
          (value: string) => { this.change.emit(value); },
          (error) => { console.log(error); }
        ));
      }
    
      onInputChange(event: any) {
        this.debouncer.next(event.target.value);
      }
    
      ngOnDestroy() {
        for (const sub of this.subs) {
          sub.unsubscribe();
        }
      }
    }

提交回复
热议问题