Debouncetime in Angular6 ngModelChange

后端 未结 2 1873
不知归路
不知归路 2021-01-18 07:44

I have a complex calculator app written in Angular6 which calculates the results based of several inputs in the ngModelChange event and to show these results in charts direc

相关标签:
2条回答
  • 2021-01-18 08:15

    you can always implement this using Subjects like below :

    declare a Subject :

    customInput : Subject<string> = new Subject();

    in your template :

    (ngModelChange)='inputValueChanged($event)'

    So now listent to the event :

      inputValueChanged(event){
          this.customInput.next(event);
      }
    

    You'll have to subscribe to your Subject in the below way :

    this.customInput.debounceTime(300).distinctUntilChanged().subscribe(value =>{
           //value will have your input
        });
    

    (with this your code will look neat and clean and also organised )

    Edit : With rxjs >= v6 ,

    Complete example can be found here

    import { Subject } from 'rxjs';
    import { debounceTime, distinctUntilChanged} from 'rxjs/operators';
    
    
    this.customInput.pipe(debounceTime(300),distinctUntilChanged()).subscribe(value =>{
     //value will have your input
    });
    
    0 讨论(0)
  • 2021-01-18 08:31

    I solved this for now with help of this question: debounceTime & distinctUntilChanged in angular 6

    So I created a Viewchild for Every Input and placed them in an array. And in the ngAfterViewInit I call this method:

    setInputEvent() {
     let inputArray = this.fillViewChildsInArray();
     for (let element of inputArray) {
        this.input$ = fromEvent(element.nativeElement, 'input')
        .pipe(
           debounceTime(1000),
           map((e: KeyboardEvent) => e.target['value'])
         );
         this.input$.subscribe((val: string) => {
          this.calculate();
         });
       }
    }
    
    0 讨论(0)
提交回复
热议问题