Angular 4, How to update [(ngModel)] with a delay of 1 seconds

前端 未结 6 1614
攒了一身酷
攒了一身酷 2021-02-05 16:17

Since ngModel is updating instantly how to put a delay.

  

        
6条回答
  •  無奈伤痛
    2021-02-05 16:24

    Answer by Fredrik Lundin updated for Angular 6:

    Template:

    
    

    Component:

    import ......
    
    import { Subject, EMPTY } from 'rxjs';
    import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
    
    @Component{(
      ...
    )}
    export class YourComponent implements OnDestroy {
    
      term$ = new Subject();
    
      private searchSubscription: Subscription;
    
      constructor() {
        this.searchSubscription = this.term$.pipe(
          debounceTime(1000),
          distinctUntilChanged(),
          switchMap(term => {
            /*do something*/
            return EMPTY;
          })
        ).subscribe();
      }
    
      ngOnDestroy() {
        //remember to unsubscribe on destroy
    
        if (this.searchSubscription) {
          this.searchSubscription.unsubscribe();
          this.searchSubscription = null;
        }
      }
    }
    

提交回复
热议问题