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

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

Since ngModel is updating instantly how to put a delay.

  

        
6条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-05 16:30

    Rxjs and Observables are the perfect candidate for this type of task! Here is an example of how it can be achieved:

    Template:

    
    

    Component:

    import ......
    
    import {Subject} from 'rxjs/Subject';
    import 'rxjs/add/operator/debounceTime';
    import 'rxjs/add/operator/distinctUntilChanged';
    import 'rxjs/add/operator/switchMap';
    
    @Component{(
      ...
    )}
    export class YourComponent {
    
      term$ = new Subject();
    
      constructor() {
        this.term$
          .debounceTime(1000)
          .distinctUntilChanged()
          .switchMap(term => /*do something*/);
      }
    }
    

    subject is a type of object that acts both as an observable and observer - meaning you can both subscribe to it and emit values from it (with next())!

    debounceTime waits for the provided time in ms until it allows for new changes

    distinctUntilChanges will not allow the same input to pass through two times in a row

    switchMap takes the latest observable from the chain so you don't get multiple results at once

提交回复
热议问题